The List class and the primitive array data structure in Java are both mechanisms to store and access a collection of objects. The ArrayList class is a resizable-array implementation of the List interface where internally the ArrayList has an array of objects.
Java APIs often have methods that require either an array of objects or a List so there are mechanisms in Java to convert from a primitive array to a List and vice versa.
Converting primitive Array to a List
Use Arrays.asList()
to convert from an array to a List.
Integer[] array = new Integer[] { 95, 87, 83 };
List<Integer> list = Arrays.asList(array);
System.out.println(list); // [95, 87, 83]
Converting List to a primitive Array
If want to convert a List to Array use toArray() method.
Integer[] array2 = list.toArray(new Integer[array.size()]);
Likewise, if want to convert primitive int values to List can simply iterate over the values and add them.
int[] array3 = new int[] { 95, 87, 83 };
List<Integer> list3 = new ArrayList<Integer>(array3.length);
for(int val : array3) {
list3.add(val);
}
System.out.println(list3); // [95, 87, 83]
Similarities and Differences between List and primitive array
Both List and primitive arrays both have the first element with an index of 0 and the nth element has an index of n - 1. Accessing an element with index less than 0 or greater than n-1 results in an exception: IndexOutOfBoundsException in list or ArrayIndexOutOfBoundsException in case of the array.
Get and set elements in primitive array
int grade = array[0];
array[0] = 98;
int len = array.length; // number of elements in array
grade = array[-1]; // throws ArrayIndexOutOfBoundsException
Get and set elements in List
int grade = list.get(0);
list.set(0, 98);
int len = list.size(); // number of elements in list
grade = list.get(-1); // throws IndexOutOfBoundsException
Unless the list is immutable (or read-only) then you can add or remove elements from it. See Collections.unmodifiableList(). To grow/shrink a primitive array, you must create a new array and copy of old elements from the old to new array.
In general, primitive arrays and Lists are semantically equivalent but with different syntax. One form can be converted to the other.