Exclude when using System.arraycopy to copy to ArrayList, gets: ArrayStoreException: null

I have some problems when trying to copy two arrays. Consider the 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()); 

The console shows: java.lang.ArrayStoreException: null. What could be wrong in this code or how can I do it differently. Sorry, maybe a difficult question, but I got stuck on it for several hours and cannot fix it.

+4
source share
4 answers

System.arraycopy expects arrays (for example, Integer []) as array parameters, not ArrayLists.

If you want to make a copy of a list like this, follow these steps:

 List<Integer> t2 = new ArrayList<Integer>(t1); 
+12
source

You need Collections#copy

 Collections.copy(t1,t2); 

It will copy all the items from the list t1 to t2.

+3
source

If someone wants to add only part of the second ArrayList, you can do this as follows:

 ArrayList<Integer> t1 = new ArrayList<Integer>(); Integer i1 = new Integer(1); Integer i2 = new Integer(2); Integer i3 = new Integer(3); t1.add(i1); t1.add(i2); t1.add(i3); ArrayList<Integer> t2 = new ArrayList<Integer>(); /* * will add only last two integers * as it creates a sub list from index 1 (incl.) * to index 3 (excl.) */ t2.addAll(t1.subList(1, 3)); System.out.println(t2.size()); // prints 2 System.out.println(t2.get(0)); // prints 2 System.out.println(t2.get(1)); // prints 3 
+1
source

easier:

 ArrayList<Integer> t2 = new ArrayList<Integer>(t1); 

or if t2 is already created

 t2.clear(); t2.addAll(t1); 
0
source

All Articles