Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get exception while using System.arraycopy for copy to ArrayList, gets: ArrayStoreException: null

I have some trouble while trying to copy two arrays. Consider following simple code:

    ArrayList<Integer> t1 = new ArrayList<Integer>();
    Integer i1 = new Integer(1);
    Integer i2 = new Integer(2);
    t1.add(i1);
    t1.add(i2);

    ArrayList<Integer> t2 = new ArrayList<Integer>();
    System.arraycopy(t1, 0, t2, 0, t1.size());

Console shows: java.lang.ArrayStoreException: null . What can be wrong in this code, or how can I do it in different way. Sorry about may be easy question but I'm stuck on this for some hours and can't fix it.

like image 339
gadon Avatar asked Feb 18 '13 14:02

gadon


2 Answers

System.arraycopy expects arrays (e.g. Integer[]) as the array parameters, not ArrayLists.

If you wish to make a copy of a list like this, just do the following:

List<Integer> t2 = new ArrayList<Integer>(t1);
like image 182
Eric Galluzzo Avatar answered Oct 12 '22 23:10

Eric Galluzzo


You need Collections#copy

Collections.copy(t1,t2);

It will copies all of the elements from t1 list into t2.

like image 24
Subhrajyoti Majumder Avatar answered Oct 12 '22 22:10

Subhrajyoti Majumder