5

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.

4 Answers 4

12

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);
Sign up to request clarification or add additional context in comments.

Comments

3

You need Collections#copy

Collections.copy(t1,t2);

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

Comments

1

In case anybody wants to add just a portion of the second ArrayList, one might do it like this:

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

Comments

0

easier:

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

or if the t2 has already been created

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.