Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int[] into ArrayList [duplicate]

What is best way recopying int[] array elements into ArrayList?

I need to do this fast so what would be the fastest way?

like image 380
Streetboy Avatar asked Apr 22 '12 15:04

Streetboy


People also ask

Can integer array convert to ArrayList?

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.

Can you convert array to ArrayList?

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.

Can we convert array to list in Java?

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.


2 Answers

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]));
like image 73
Mattias Isegran Bergander Avatar answered Oct 05 '22 17:10

Mattias Isegran Bergander


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));
like image 36
Matt Ball Avatar answered Oct 05 '22 17:10

Matt Ball