[Ljava.lang.Object; cannot be applied to [Ljava.util.ArrayList;

In my java code, I am trying to create an arraylist list, my code is as follows:

private ArrayList<Integer>[] listoflist; listoflist = (ArrayList<Integer>[]) new Object[875715]; 

However, when I compile the code, the compiler keeps saying that

[Ljava.lang.Object; cannot be applied to [Ljava.util.ArrayList;

May I ask why I cannot pass Object [] to ArrayList []?

+7
source share
4 answers

You said you were trying to create a list of ArrayLists. But ... you are trying to use an array for this ... Why not just use another ArrayList? This is actually pretty easy:

 private List<List<Integer>> listoflist = new ArrayList<ArrayList<Integer>>(); 

Here is an example of its use:

 ArrayList<Integer> list1 = new ArrayList<Integer>(); list1.add(Integer.valueOf(3)); list1.add(Integer.valueOf(4)); ArrayList<Integer> list2 = new ArrayList<Integer>(); list2.add(Integer.valueOf(6)); list2.add(Integer.valueOf(7)); listoflist.add(list1); listoflist.add(list2); 

Saying ArrayList<ArrayList<Integer>> so strange a lot of times, so in Java 7 the construct might just be new ArrayList<>(); (it infers the type from the variable you assign).

+4
source

Java is a strong typed language - therefore, you cannot just pass one type to another. However, you can convert them.

In the case of Object[] to List just use

 Object[] arr = new Object[]{...}; List<Object> list = Arrays.asList(arr); 

and if you want to use it as an ArrayList , for example. if you want to add some other elements just wrap it again

  ArrayList<Object> arrList = new ArrayList<Object>(Arrays.asList(arr)); 
+4
source

You can make an n-dimensional ArrayList, like an n-dimensional array, by placing ArrayLists in ArrayLists.

Here is an example with 3 dimensions to show the concept.

 public static void main(String args[]){ ArrayList<ArrayList<ArrayList<Integer>>> listOfListOfList = new ArrayList<ArrayList<ArrayList<Integer>>>(); int firstDimensionSize = 3; int secondDimensionSize = 4; int thirdDimensionSize = 5; for (int i = 0; i < firstDimensionSize; i++) { listOfListOfList.add(new ArrayList<ArrayList<Integer>>(vertices)); for (int j = 0; j < secondDimensionSize; j++) { listOfListOfList.get(i).add(new ArrayList<Integer>()); for(int k = 0; k < thirdDimensionSize; k++) { listOfListOfList.get(i).get(j).add(k); } } } } 

Note that you can leave <> empty after the new ArrayList <>. Java will infer the type (no matter how nested), since java 7 I count. I just wrote them in this example to show what type you are processing at each level to make the example more understandable. You can still write them down to make your code more readable.

+1
source

define it in one line, as shown below, the compiler does not complain

 private ArrayList[] listoflist = (ArrayList<Integer>[]) new Object[10]; 
-2
source

All Articles