Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list to array. java.lang.ArrayStoreException

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]
like image 771
Klausos Klausos Avatar asked Jan 13 '12 10:01

Klausos Klausos


4 Answers

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.

like image 104
Thomas Avatar answered Nov 17 '22 00:11

Thomas


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));
like image 27
adarshr Avatar answered Nov 17 '22 02:11

adarshr


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[]

like image 32
Peter Lawrey Avatar answered Nov 17 '22 00:11

Peter Lawrey


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

like image 1
Shivan Dragon Avatar answered Nov 17 '22 00:11

Shivan Dragon