Converting Object[] to ArrayList<V>[] in Java - java

The following code throws an ClassCastException:
ArrayList<V>[] table = (ArrayList<V>[]) new Object[tableSize];
How can I create an Array of ArrayList if this doesn't work?
EDIT:
To be shure everybody understands the problem. I need an Array that contains multiple ArrayLists.
EDIT2:
tableSize is an int.

EDIT: OK, here is what you can do:
ArrayList<String>[] table = new ArrayList[tableSize];
It compiles and works on Java 8 i'm using.

In case of Java you can not create new instance of array that type is generic.
T[] array = new T[size]; - cause compile error Cannot create a generic array of T.
The same error will be present when you will try to use it
ArrayList<T>[] array = new ArrayList<T>[size];
With the same reason. The Java runtime does not know what is T after compilation therefor will not be able to allocate valid memory space.
To pass this issue you have following options:
Remove the generic type and use a raw.
ArrayList[] array =new ArrayList[size];
Use list of a list
List<List<T>> list = new ArrayList<List<T>>();

Not the smoothest way to do it But if I got your question correctly something like this should do the trick:
int tableSize = 2;
Collection<String> listWithItems = new ArrayList<>();
listWithItems.add("Foo");
listWithItems.add("Bar");
Collection<Collection<String>> listOfList = new ArrayList<>();
listOfList.add(listWithItems);
Object[] array = listOfList.toArray(new Object[tableSize]);
System.out.println("Col: " + listOfList);
System.out.println("Array: " + Arrays.toString(array));
Print out is:
Col: [[Foo, Bar]]
Array: [[Foo, Bar], null]
Short example without extra "fluff" to get the inital array:
Object[] theArrayOfLists = new ArrayList<List<SomeClass>>().toArray(new Object[tableSize]);

Related

Storing an ArrayList in an 2d Array Java

How can I store an ArrayList in a two dimensional array?
I've tried it like this, but it won't work:
ArrayList<Integer> arrList = new ArrayList<Integer>();
ArrayList<Integer>[][] arr = new ArrayList<Integer>[9][9];
but it won't even let me declare the ArrayList-Array.
Is there a way to store a list in a 2d array?
Thanks in advance!
You can't create arrays of generic types in Java. But this compiles:
ArrayList<Integer> arrList = new ArrayList<Integer>();
ArrayList<Integer>[][] arr = (ArrayList<Integer>[][]) new ArrayList[9][9];
arr[0][0] = arrList;
Why can't you create these arrays? According to the Generics FAQ, because of this problem:
Pair<Integer,Integer>[] intPairArr = new Pair<Integer,Integer>[10]; // illegal
Object[] objArr = intPairArr;
objArr[0] = new Pair<String,String>("",""); // should fail, but would succeed
Assuming you want an ArrayList inside an ArrayList inside yet another ArrayList, you can simply specify that in your type declaration:
ArrayList<ArrayList<ArrayList<Integer>>> foo = new ArrayList<ArrayList<ArrayList<Integer>>>();
Entries can be accessed via:
Integer myInt = foo.get(1).get(2).get(3);
Just be wary of boundaries - if you try to access an out of bounds index you'll see Exceptions thrown.

How to add values to Double[] arraylist [duplicate]

This question already has answers here:
I'm getting an error in my Java code but I can't see whats wrong with it. Help?
(5 answers)
Closed 5 years ago.
I created this arrayList:
Double[] arrayOfNumbers = new Double[List.size()];
And I try to add it numbers with this:
arrayOfNumbers.add(0.9);
This gives me an error message that says:
Cannot invoke add(double) on the array type Double[]
So, how can I add that value in this Double[] arraylist?
That is not an ArrayList. That is an array.
You can declare an arraylist of doubles as :
int initialCapacity = 20;
List<Double> doubles = new ArrayList<Double>(initialCapacity);
doubles.add(0.9);
You can add more than 20 values in an ArrayList even though the initial capacity is specified as 20.
But to declare an array and populate it:
double[] doublesArray = new doubles[20];
doubles[0] = 0.9;
doubles[1] = 0.5;
.....
doubles[19] = 0.7; // 19 is the last index for an array of size 20.
If you add more than 20 here, you will get ArrayIndexOutOfBoundsException
Double[] is not ArrayList to add to an array you can use :
Double[] arrayOfNumbers = new Double[List.size()];
arrayOfNumbers[0] = 0.9;
Instead to add to an ArrayList you can use :
List<Double> arrayOfNumbers = new ArrayList<>();
arrayOfNumbers.add(0.9);
Arrays and lists are different things. Arrays don't have an add method, but are assignable by the subscript ([]) operator:
arrayOfNumbers[0] = 0.9;
Double[] arrayOfNumbers = new Double[List.size()] is not a List
it is an array.
We declare arrays with [] and lists with <> and generics.
For example `
int[]arr=new int[3] is an array of 3 ints, but List<Integer>list=new ArrayList<>() is a list of integers(not primitive ints you CANNOTwrite code like this List<int>=new ArrayList<>()
Hope that helps!
java.util.List is a different that an array(which has limited predefined size).
you can't declare/perform as above you did in question, java compiler will complain if you do so.
you are phasing a error like,
Cannot invoke add(double) on the array type Double[]
because an array(arrayOfNumbers) do not having a such method(add) which you can execute on arrayOfNumbers.
However,
general syntax to initialize of an array of any type(here in example, Integer taken FYI) is likewise,
int intArray[] = {1,2,3}; // initialize at the time of creation
or
int arrayOfNumbers [] = new int[] {1, 2, 3};
or
intArray[index] = 1;
Moreover, you can switch from array to List & vice-versa as likewise,
List<Integer> list = java.util.Arrays.asList(arrayOfNumbers);
or
Integer [] intArray = list.toArray(new Integer[list.size()]);
A List is an Interface that extends another interface called Collection, so a List is-a Collection. An Interface defines and describes behavior, it defines a contract that another class must conform to, and one of the classes that does so is called java.util.ArrayList, and add() is one behaviour defined in the List contract, because a List must have the ability for things to be added to it. An ArrayList is one type of a List. What you have created is NOT an ArrayList, it is an Array.
An array is a primitive data structure, once created, it's size cannot be changed, If you wish to add a new element to an array you have to create a new array that is bigger, then transfer all elements from the old array to the new one. Under the covers an ArrayList does exactly that. THIS IS HOW YOU CREATE an ArrayList :
//a list of Objects of type `Double`
List<Double> listOfNumbers = new ArrayList<>();
if you wish to add an element to this list, you would do this :
listOfNumbers.add(5.2);
You do seem like you still need to read a beginners book and practice basic Java programming. I would like to suggest this playlist
This will really be helpful to you, and remember you can only learn something by doing it hands-on, NOT by just watching somebody else doing it.

java - "int cannot be converted to ArrayList"

I'm trying to create a two dimensional ArrayList which will store ints, strings & booleans.
I've got as far as entering the first int, but I get a red squiggle and the error "int cannot be converted to ArrayList".
ArrayList[][] qarray= new ArrayList [10][5];
qarray[0][0]= 1;
BTW, googling the phrase "int cannot be converted to ArrayList" is giving me exactly six results.
The error is correct.
Your array type is ArrayList. You can insert only ArrayLists in that array.
If you want to store int's, your declaration should be.
int[][] qarray= new int [10][5];
And also, as someone commented, you cannot store strings and booleans in this array anymore.
ArrayList[][] qarray= new ArrayList [10][5];
Basically your code creates 2 dimensional array list objects (50 array list objects).
qarray[0][0]= 1;
And you are trying to assign integer, where you need to create a ArrayList object. It expects something like
qarray[0][0]= new ArrayList();
However this would not meet your objective. The following piece of code could meet your objectives:
ArrayList[] qarray = new ArrayList[10];
qarray[0]= new ArrayList();
qarray[0].add(1);
qarray[1]= new ArrayList();
qarray[1].add(true);
qarray[2]= new ArrayList();
qarray[2].add("hello");
Try like this:
List<Integer> qarray = new ArrayList<>();
qarray.add(1);
First I believe that you need array and not ArrayList. 2d array can be created as following.
int[][] arr = new int [10][10];
Your next problem is that you tried to assign int constant 1 to variable of other type. The following example shows how to assign int to element of array
arr [0][0] = 1;
According to javadoc, you can not create arrays of ArrayList. Use 2D array instead.
If you need 2D ArrayList anyway, you should have tried this way:
ArrayList<ArrayList<Integer>> listOfLists = new ArrayList<>();
ArrayList<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(2);
ArrayList<Integer> list2 = new ArrayList<>();
list2.add(5);
listOfLists.add(list1);
listOfLists.add(list2);
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
you wan to add int,String and boolean then you can use
ArrayList<ArrayList<Object>> listOfLists = new ArrayList<ArrayList<Object>>();
it will help you
ArrayList<Integer>[][] list = new ArrayList[10][10];
list[0][0] = new ArrayList<>();
list[0][0].add(new Integer(10);
try like this.

Can someone break down this line so I can understand it?

I'm having trouble understanding how an array of ArrayLists is initialized in Java, can someone explain what's going on in this line of code?
edges = (ArrayList<Integer>[]) new ArrayList[nodeCount + 1];
Let's break it space-by-space.
edges is a variable of type ArrayList<Integer>[]
= is the assign operator which assignes the right-hand to the left-hand
(ArrayList<Integer>[]) is a cast of a variable to the type.
new ArrayList[nodeCount + 1] means we allocate space for an array of ArrayList with nodeCount+1 unknown elements.
This is a very bad way of initializing an array. What it does is it creates an array and makes the elements into Integers.
An alternative:
edges = new ArrayList<Integer>(nodeCount+1);
Explanation: The ArrayList class has a constructor which can specify its length*, this is what I use here.
Note: According to #Rohit Jain, it doesn't specify the length, but the initial capacity.
You cannot create an array whose component type is parameterized type. It's not type safe. Although you can create an array whose component type is raw type, but that won't be type safe either. Consider the following example:
List<Integer>[] list = null; // Declaration is OK
list = new ArrayList<Integer>[5]; // Compiler error: Generic array creation
list = new ArrayList[5]; // Compiles fine. But not safe. Gives warning
Suppose you created an array of raw types. Let's see what can be the implication:
List<Integer>[] list = new ArrayList[10]; // Not type safe
Object[] objArr = list; // We can assign List<Integer>[] to Object[]
// We can add even ArrayList<String> in Object[]
// This will successfully compile, and run.
objArr[0] = new ArrayList<String>() {
{
add("rohit"); add("jain");
}
};
// Here's the problem. It will compile fine, but at runtime will throw
// ClassCastException
Integer val = list[0].get(0);
Alternative is create a List of List:
List<List<Integer>> edges = new ArrayList<List<Integer>>();
Suggested Read: -
Angelika Langer Generic FAQs:
Can I create an array whose component type is a concrete parameterized type?
Can I declare a reference variable of an array type whose component type is a concrete parameterized type?
In the above line you are creating an array of ArrayList, you could replace ArrayList by a more simple type to help you to understand, e.g. an array of String:
edges = (String[]) new String[nodeCount + 1];
nodeCount + 1 corresponds to size of the array. The array can't have more than this number of elements.
Note that using an array of a parametrized ArrayList is quite strange and prone to misunderstanding and errors. I would use a List<List<Integer>> here, e.g.:
edges = new ArrayList<List<Integer>>();
this line defines an array, like any other array out there: exampe new Object[0], new String[0], ...
and just like any other array, the values will be initiated with the null value. for primitive types is that '0', for objects/classes is that null.
so you should initiate the different arraylists before using it like:
edges = new ArrayList<Integer>[nodeCount + 1];
for(int i=0; i<edges.length; i++){
edges[i] = new ArrayList<Integer>();
}
This does not initialize an ArrayList -- it initializes an array of ArrayLists:
new ArrayList[nodeCount + 1] = create an array of ArrayList objects with nodeCount + 1 slots
(ArrayList<Integer>[]) = cast it to an "array of ArrayList objects which in turn may only contain Integer objects". This is needed because the array declaration syntax of java apparently can't handle generics (just tried it -- I never needed this before).
It could be a misunderstanding, and the writer actually wanted to initialize one ArrayList with a capacity of nodeCount+ 1. The correct code for that would be
edges = new ArrayList<Integer>(nodeCount + 1);
Actually the capacity parameter is just an optimization, since ArrayList objects grow automatically as needed. But if you already know how many entries you need, the List can be created with enough capacity from the start.
new ArrayList[nodeCount + 1]
create a new array of ArrayList, its length is nodeCount + 1;
then
(ArrayList<Integer>[])
is a cast operation, it casts the array you just created into an array of ArrayList<Integer>

Convert list to array in Java [duplicate]

This question already has answers here:
Converting 'ArrayList<String> to 'String[]' in Java
(17 answers)
Closed 4 years ago.
How can I convert a List to an Array in Java?
Check the code below:
ArrayList<Tienda> tiendas;
List<Tienda> tiendasList;
tiendas = new ArrayList<Tienda>();
Resources res = this.getBaseContext().getResources();
XMLParser saxparser = new XMLParser(marca,res);
tiendasList = saxparser.parse(marca,res);
tiendas = tiendasList.toArray();
this.adaptador = new adaptadorMarca(this, R.layout.filamarca, tiendas);
setListAdapter(this.adaptador);
I need to populate the array tiendas with the values of tiendasList.
Either:
Foo[] array = list.toArray(new Foo[0]);
or:
Foo[] array = new Foo[list.size()];
list.toArray(array); // fill the array
Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way:
List<Integer> list = ...;
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i);
Update:
It is recommended now to use list.toArray(new Foo[0]);, not list.toArray(new Foo[list.size()]);.
From JetBrains Intellij Idea inspection:
There are two styles to convert a collection to an array: either using
a pre-sized array (like c.toArray(new String[c.size()])) or
using an empty array (like c.toArray(new String[0]). In
older Java versions using pre-sized array was recommended, as the
reflection call which is necessary to create an array of proper size
was quite slow. However since late updates of OpenJDK 6 this call
was intrinsified, making the performance of the empty array version
the same and sometimes even better, compared to the pre-sized
version. Also passing pre-sized array is dangerous for a concurrent or
synchronized collection as a data race is possible between the
size and toArray call which may result in extra nulls
at the end of the array, if the collection was concurrently shrunk
during the operation. This inspection allows to follow the
uniform style: either using an empty array (which is recommended in
modern Java) or using a pre-sized array (which might be faster in
older Java versions or non-HotSpot based JVMs).
An alternative in Java 8:
String[] strings = list.stream().toArray(String[]::new);
Since Java 11:
String[] strings = list.toArray(String[]::new);
I think this is the simplest way:
Foo[] array = list.toArray(new Foo[0]);
Best thing I came up without Java 8 was:
public static <T> T[] toArray(List<T> list, Class<T> objectClass) {
if (list == null) {
return null;
}
T[] listAsArray = (T[]) Array.newInstance(objectClass, list.size());
list.toArray(listAsArray);
return listAsArray;
}
If anyone has a better way to do this, please share :)
I came across this code snippet that solves it.
//Creating a sample ArrayList
List<Long> list = new ArrayList<Long>();
//Adding some long type values
list.add(100l);
list.add(200l);
list.add(300l);
//Converting the ArrayList to a Long
Long[] array = (Long[]) list.toArray(new Long[list.size()]);
//Printing the results
System.out.println(array[0] + " " + array[1] + " " + array[2]);
The conversion works as follows:
It creates a new Long array, with the size of the original list
It converts the original ArrayList to an array using the newly created one
It casts that array into a Long array (Long[]), which I appropriately named 'array'
This is works. Kind of.
public static Object[] toArray(List<?> a) {
Object[] arr = new Object[a.size()];
for (int i = 0; i < a.size(); i++)
arr[i] = a.get(i);
return arr;
}
Then the main method.
public static void main(String[] args) {
List<String> list = new ArrayList<String>() {{
add("hello");
add("world");
}};
Object[] arr = toArray(list);
System.out.println(arr[0]);
}
For ArrayList the following works:
ArrayList<Foo> list = new ArrayList<Foo>();
//... add values
Foo[] resultArray = new Foo[list.size()];
resultArray = list.toArray(resultArray);
Example taken from this page: http://www.java-examples.com/copy-all-elements-java-arraylist-object-array-example
import java.util.ArrayList;
public class CopyElementsOfArrayListToArrayExample {
public static void main(String[] args) {
//create an ArrayList object
ArrayList arrayList = new ArrayList();
//Add elements to ArrayList
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
arrayList.add("5");
/*
To copy all elements of java ArrayList object into array use
Object[] toArray() method.
*/
Object[] objArray = arrayList.toArray();
//display contents of Object array
System.out.println("ArrayList elements are copied into an Array.
Now Array Contains..");
for(int index=0; index < objArray.length ; index++)
System.out.println(objArray[index]);
}
}
/*
Output would be
ArrayList elements are copied into an Array. Now Array Contains..
1
2
3
4
5
You can use toArray() api as follows,
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("ListItem1");
stringList.add("ListItem2");
String[] stringArray = new String[stringList.size()];
stringArray = stringList.toArray(stringList);
Values from the array are,
for(String value : stringList)
{
System.out.println(value);
}
This (Ondrej's answer):
Foo[] array = list.toArray(new Foo[0]);
Is the most common idiom I see. Those who are suggesting that you use the actual list size instead of "0" are misunderstanding what's happening here. The toArray call does not care about the size or contents of the given array - it only needs its type. It would have been better if it took an actual Type in which case "Foo.class" would have been a lot clearer. Yes, this idiom generates a dummy object, but including the list size just means that you generate a larger dummy object. Again, the object is not used in any way; it's only the type that's needed.
Try this:
List list = new ArrayList();
list.add("Apple");
list.add("Banana");
Object[] ol = list.toArray();

Categories