1

here is what i have got

ArrayList<Integer> list = new ArrayList<Integer>();
    Integer a = 50; 
    Integer b = 55;
    Integer c = 98;
    Integer d = 101;
    list.add(a);
    list.add(b);
    list.add(c);
    list.add(d);

now i want to convert this "list" to an Array... e.g.:

Integer[] actual= {50,55,98,101};

anyway how to do it? thanks.

1
  • list.toArray(new Integer[0]); Commented Nov 21, 2011 at 22:11

2 Answers 2

6
Integer[] array = list.toArray(new Integer[list.size()]);

If you want an int[] array, you'll have to loop over the list and unbox each element explicitly.

See http://download.oracle.com/javase/6/docs/api/java/util/List.html next time you're looking for a method of List.

Sign up to request clarification or add additional context in comments.

1 Comment

Apache Commons Lang's ArrayUtils.toPrimitive methods can help converting between arrays of wrappers and arrays of primitives.
1

Sefirosu, for another solution you can do it using Arrays.copyOf() or Arrays.copyOfRange() too.

Integer[] integerArray = Arrays.copyOf(list.toArray(), list.toArray().length, Integer[].class);
Integer[] integerArray = Arrays.copyOfRange(list.toArray(), 0, 4, Integer[].class);

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.