So I have to variables in java
List<Integer> a = new arrayList();
List<int[]> b = new arrayList();
When I do a.toArray(new int[a.size()])
it returns an error, but I can do b.toArray(new int[b.size()][])
. I am confused.
So I have to variables in java
List<Integer> a = new arrayList();
List<int[]> b = new arrayList();
When I do a.toArray(new int[a.size()])
it returns an error, but I can do b.toArray(new int[b.size()][])
. I am confused.
You need to specify the correct type.
This should work: a.toArray(new Integer[a.size()])
.
You seem to be confusing a few things. First a
and b
aren't even close to being similar things. One is a list that contains Integer
s. Th second is a list where each member is an array of int
s
Regardless of what is in your List<T>
the toArray
method expects you to pass an array of whatever the element type of your list is (ie. T[]
). So for a
you need to pass an Integer[]
. For b
you need to pass an int[][]
.
So as shown in the other answer you need a.toArray(new Integer[a.size()])
Stealing from the comments on the answer by cybersam, if the array you pass in is of the correct size it'll be used to store the result. Technically you could just use size of 0 and then a new array will be created by the toArray
method.