From Arraylist to Array

Eddy Freeman picture Eddy Freeman · Nov 1, 2011 · Viewed 237.5k times · Source

I want to know if it is safe/advisable to convert from ArrayList to Array? I have a text file with each line a string:

1236
1233
4566
4568
....

I want to read them into array list and then i convert it to Array. Is it advisable/legal to do that?

thanks

Answer

ObscureRobot picture ObscureRobot · Nov 1, 2011

Yes it is safe to convert an ArrayList to an Array. Whether it is a good idea depends on your intended use. Do you need the operations that ArrayList provides? If so, keep it an ArrayList. Else convert away!

ArrayList<Integer> foo = new ArrayList<Integer>();
foo.add(1);
foo.add(1);
foo.add(2);
foo.add(3);
foo.add(5);
Integer[] bar = foo.toArray(new Integer[foo.size()]);
System.out.println("bar.length = " + bar.length);

outputs

bar.length = 5