What is best way recopying int[]
array elements into ArrayList
?
I need to do this fast so what would be the fastest way?
An array can be converted to an ArrayList using the following methods: Using ArrayList. add() method to manually add the array elements in the ArrayList: This method involves creating a new ArrayList and adding all of the elements of the given array to the newly created ArrayList using add() method.
We can convert an array to arraylist using following ways. Using Arrays. asList() method - Pass the required array to this method and get a List object and pass it as a parameter to the constructor of the ArrayList class.
Since List is a part of the Collection package in Java. Therefore the Array can be converted into the List with the help of the Collections. addAll() method.
ArrayList is not the best storage for primitives such as int. ArrayList stores objects not primitives. There are libraries out there for Lists with primitives.
If you really want to store all primitive int
as anInteger
object you will have to convert them one by one using Integer.valueOf(...)
(so you don't create extra Integer instances when not needed).
While you can do this:
List<Integer> list = Arrays.asList(1, 2, 3);
You cannot do this:
int[] i = { 1, 2, 3 };
List<Integer> list = Arrays.asList(i); // this will get you List<int[]>
as an array is actually an object as well an treated as such in var-args when using primitives such as int. Object arrays works though:
List<Object> list = Arrays.asList(new Object[2]);
So something along the lines of:
int[] array = { 1, 2, 3 };
ArrayList<Integer> list = new ArrayList<Integer>(array.length);
for (int i = 0; i < array.length; i++)
list.add(Integer.valueOf(array[i]));
Use Arrays#asList(T... a)
to create "a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)"
Integer[] intArray = {1, 2, 3, 42}; // cannot use int[] here
List<Integer> intList = Arrays.asList(intArray);
Alternatively, to decouple the two data structures:
List<Integer> intList = new ArrayList<Integer>(intArray.length);
for (int i=0; i<intArray.length; i++)
{
intList.add(intArray[i]);
}
Or even more tersely:
List<Integer> intList = new ArrayList<Integer>(Arrays.asList(intArray));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With