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]
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.
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));
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[]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With