Reputation: 16060
There is a list:
List<Integer[]> myList = new ArrayList<Integer[]>();
It contains a sigle entry, but might contain multiple entries:
myList = [[2,null,1,null,null,3,6,1,1]]
I need to convert this list into the array Integer[][]
, but the conversion fails due to nulls:
Integer[] myArr = myList.toArray(new Integer[myList.size()]);
How to solve this issue?
Edit#1
I need to get:
myArr = [2,null,1,null,null,3,6,1,1]
Upvotes: 20
Views: 43164
Reputation: 62623
Works for me
List<Integer[]> myList = new ArrayList<Integer[]>();
Integer[] ia = {2,null,1,null,null,3,6,1,1};
myList.add(ia);
Integer[][] iaa = myList.toArray(new Integer[myList.size()][]);
System.out.println(Arrays.deepToString(iaa));
Upvotes: 2
Reputation: 88757
Try this (assuming you have actually the List<Integer[]>
you talked about in your comment):
List<Integer[]> myList = new ArrayList<Integer[]>();
myList.add(new Integer[] {2,null,1,null,null,3,6,1,1} );
Integer[][] myArr = myList.toArray(new Integer[myList.size()][]);
If you convert a list of arrays to an array, you'll get a 2 dimensional array and thus your parameter should be one too.
Upvotes: 13
Reputation: 15229
Are you sure that's what you're doing. I've tried this code and it works fine:
List<Integer> myList = new ArrayList<Integer>();
myList.add(2);
myList.add(null);
myList.add(1);
Integer[] myArr = myList.toArray(new Integer[myList.size()]);
for(Integer i:myArr) {
System.out.println(i);
}
Displaying "2,null,1".
However if in the "for loop" I change "Integer i" to "int i" the autoboxing fails with a NullPointerException on the null element.
As long as you make an array on Integer objects (not int primitives) and treat that array's elements as Integer objects (not do something that will trigger an autoboxing/unboxing) you should be fine.
Otherwise, you just have to manually remove all nulls from your List before turning it to an array
Upvotes: 1
Reputation: 533890
If you have a
List<Integer[]> myList = new ArrayList<Integer[]>();
with only one array in it, you can do
Integer[] myArr = myList.get(0);
null
never causes an ArrayStoreException for a new Integer[]
Upvotes: 1