Moving between arrays and collections
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Arrays and collections often meet: an old method returns a String[], but you want a List you can grow; or a list is ready, but a method needs an array. The conversion methods look simple, yet each one has a rule that surprises people.
Arrays.asList is a view, not a copy
A view is a collection that has no storage of its own: it reads and writes another object. Arrays.asList(array) is a view on the array, so a change through one shows in the other.
A String[] becomes a list with Arrays.asList. The first program changes the list and the array in turn; the second shows the crash when you try to add.
Example 1 · Arrays.asList writes through
import java.util.Arrays;import java.util.List;
public class WriteThroughDemo { public static void main(String[] args) { String[] coaches = {"S1", "S2", "S3"}; List<String> list = Arrays.asList(coaches);
list.set(0, "A1"); System.out.println("Array after list.set: " + Arrays.toString(coaches));
coaches[2] = "B1"; System.out.println("List after array change: " + list);
System.out.println("Same size: " + (list.size() == coaches.length)); }}Array after list.set: [A1, S2, S3] List after array change: [A1, S2, B1] Same size: true
What this code does
list.set(0, "A1")changedcoaches[0], andcoaches[2] = "B1"showed up in the list. There is only one set of boxes.- The list's size is always the array's length, because the list has no storage of its own.
Example 2 · Common mistake: adding to Arrays.asList
import java.util.Arrays;import java.util.List;
public class AsListAddDemo { public static void main(String[] args) { List<String> waiting = Arrays.asList("Ramesh", "Suresh"); System.out.println("Waiting list: " + waiting); waiting.add("Mahesh"); System.out.println("Waiting list: " + waiting); }}Waiting list: [Ramesh, Suresh] Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.AbstractList.add(AbstractList.java:155) at java.base/java.util.AbstractList.add(AbstractList.java:113) at AsListAddDemo.main(AsListAddDemo.java:8)
What this code does
- The program compiles, prints the first line, and then
addthrowsUnsupportedOperationExceptionfromAbstractList.add. - The array behind the list has exactly two boxes, so the list cannot grow.
Arrays.asList(arr) does not copy anything. It returns a list that sits on top of the array, like a window. Both share the same boxes in memory, so list.set(0, x) changes the array, and arr[0] = x changes the list. This is called write-through.
Because the array cannot grow or shrink, the list cannot either. It is fixed-size: set works, but add and remove throw UnsupportedOperationException. The compiler cannot catch this, because the variable type is just List.
Arrays.asList is different from List.of: it allows set and null items, while List.of allows neither.Getting a list you can change
Three ways to get a changeable list or a read-only copy from the same array: new ArrayList<>(...), List.of and Collections.addAll.
Example 3 · The fix: three ways to get a list
import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.List;
public class ThreeWaysDemo { public static void main(String[] args) { String[] booked = {"Ramesh", "Suresh"};
List<String> waiting = new ArrayList<>(Arrays.asList(booked)); waiting.add("Mahesh"); waiting.remove("Ramesh"); System.out.println("Own list: " + waiting); System.out.println("Array untouched: " + Arrays.toString(booked));
List<String> snapshot = List.of(booked); booked[0] = "Dinesh"; System.out.println("List.of copy: " + snapshot); System.out.println("Array now: " + Arrays.toString(booked));
List<String> extra = new ArrayList<>(); Collections.addAll(extra, booked); System.out.println("addAll copy: " + extra); }}Own list: [Suresh, Mahesh] Array untouched: [Ramesh, Suresh] List.of copy: [Ramesh, Suresh] Array now: [Dinesh, Suresh] addAll copy: [Dinesh, Suresh]
What this code does
new ArrayList<>(Arrays.asList(booked))is a separate list. AddingMaheshand removingRameshdid not touch the array.List.of(booked)is a frozen copy: changingbooked[0]later did not change it.Collections.addAllcopied the current array items into a list.
Wrap the view in a new ArrayList to get your own, growable copy: new ArrayList<>(Arrays.asList(arr)). The new list copies the items once; after that, the list and the array are independent. Pick the conversion by what you need:
Arrays.asList(arr): fixed-size view;setwrites into the array; noaddorremove.new ArrayList<>(Arrays.asList(arr)): your own copy; add, remove and set freely.List.of(arr): read-only copy; later array changes do not show;nullitems throwNullPointerException.Collections.addAll(list, arr): add every array item to a list you already have.
The primitive array trap
An int[] and an Integer[] behave differently in Arrays.asList. The program compares the list sizes, then converts an int[] to a list and back with loops.
Example 4 · The int[] trap and its fix
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class PrimitiveTrapDemo { public static void main(String[] args) { int[] runs = {12, 45, 7, 45};
List<int[]> wrong = Arrays.asList(runs); System.out.println("Size of wrong list: " + wrong.size());
Integer[] boxed = {12, 45, 7, 45}; List<Integer> right = Arrays.asList(boxed); System.out.println("Size of right list: " + right.size()); System.out.println("Contains 45: " + right.contains(45));
List<Integer> fromLoop = new ArrayList<>(); for (int r : runs) { fromLoop.add(r); } System.out.println("Built with a loop: " + fromLoop);
int[] back = new int[fromLoop.size()]; for (int i = 0; i < back.length; i++) { back[i] = fromLoop.get(i); } System.out.println("Back to int[]: " + Arrays.toString(back)); }}Size of wrong list: 1 Size of right list: 4 Contains 45: true Built with a loop: [12, 45, 7, 45] Back to int[]: [12, 45, 7, 45]
What this code does
Arrays.asList(runs)with anint[]gives aList<int[]>holding one item: the whole array.- With
Integer[], each value is an item. Forint[], a loop boxes values into aList<Integer>, and another loop unboxes them back.
Collections hold objects, never primitives. So Arrays.asList(intArray) cannot turn each int into an item. Instead, Java treats the whole int[] as one object, and you get a List<int[]> with size 1. It compiles, so the bug hides until contains(45) quietly returns false.
For an Integer[], Arrays.asList works as expected. For an int[], use a loop: for (int r : runs) list.add(r); boxes each value. Going back from List<Integer> to int[] also needs a loop, and each list.get(i) is unboxed. A null item in the list then throws NullPointerException.
From a list to an array
Going the other way, toArray() and toArray(new String[0]) give different array types. The program prints both and then tries a cast.
Example 5 · From a list to a typed array
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class ToArrayDemo { public static void main(String[] args) { List<String> passengers = new ArrayList<>(List.of("Anil", "Bina", "Chitra"));
Object[] objects = passengers.toArray(); System.out.println("toArray(): " + objects.getClass().getSimpleName());
String[] names = passengers.toArray(new String[0]); System.out.println("toArray(new String[0]): " + names.getClass().getSimpleName()); System.out.println("First name in upper case: " + names[0].toUpperCase());
String[] big = new String[5]; String[] same = passengers.toArray(big); System.out.println("Used my array: " + (same == big) + " " + Arrays.toString(big));
try { String[] bad = (String[]) passengers.toArray(); System.out.println(bad.length); } catch (ClassCastException e) { System.out.println("Cast failed: " + e.getClass().getSimpleName()); } }}toArray(): Object[] toArray(new String[0]): String[] First name in upper case: ANIL Used my array: true [Anil, Bina, Chitra, null, null] Cast failed: ClassCastException
What this code does
toArray()givesObject[], so casting it toString[]fails at run time.toArray(new String[0])gives a realString[].- When the passed array is big enough, Java fills it and returns the same array; the extra boxes stay
null.
list.toArray() with no argument returns an Object[]. You cannot cast it to String[]; the cast compiles but throws ClassCastException, because the real object is an Object[].
Pass an array of the right type instead: list.toArray(new String[0]). Java sees the type String[], makes a new array of exactly the right size and fills it. If you pass a big enough array, Java fills that one and puts null after the last item.
Arrays.sort or Collections.sort?
Arrays.sort sorts arrays and Collections.sort sorts lists. The program sorts an int[], an Integer[] from high to low, part of an array, and a list.
Example 6 · Arrays.sort versus Collections.sort
import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.List;
public class SortBothDemo { public static void main(String[] args) { int[] marks = {67, 92, 54, 81, 75}; Arrays.sort(marks); System.out.println("int[] sorted: " + Arrays.toString(marks)); System.out.println("Index of 81: " + Arrays.binarySearch(marks, 81));
Integer[] boxed = {67, 92, 54, 81, 75}; Arrays.sort(boxed, Collections.reverseOrder()); System.out.println("Integer[] high to low: " + Arrays.toString(boxed));
int[] partly = {9, 8, 7, 6, 5, 4}; Arrays.sort(partly, 1, 4); System.out.println("Only index 1 to 3 sorted: " + Arrays.toString(partly));
List<String> subjects = new ArrayList<>(List.of("Physics", "Maths", "Chemistry")); Collections.sort(subjects); System.out.println("List sorted: " + subjects); subjects.sort(Collections.reverseOrder()); System.out.println("List reversed: " + subjects); }}int[] sorted: [54, 67, 75, 81, 92] Index of 81: 3 Integer[] high to low: [92, 81, 75, 67, 54] Only index 1 to 3 sorted: [9, 6, 7, 8, 5, 4] List sorted: [Chemistry, Maths, Physics] List reversed: [Physics, Maths, Chemistry]
What this code does
Arrays.sortsorts theint[]in place, andbinarySearchthen finds 81 at index 3. For high to low order, the values must beInteger[].Arrays.sort(partly, 1, 4)sorted only indexes 1, 2 and 3. Lists useCollections.sortorlist.sort.
Arrays.sort sorts arrays; Collections.sort and list.sort sort lists. For an int[] or double[], Arrays.sort has no Comparator version, so Arrays.sort(marks, Collections.reverseOrder()) does not compile. Use an Integer[], or sort ascending and read the array from the end.
Arrays.sort(arr, from, to) sorts only part of an array, from index from up to but not including to. For objects, both sorts are stable: equal items keep their old order. Arrays.binarySearch needs a sorted array, just like Collections.binarySearch needs a sorted list.
Fix the error
Fix the conversion
Read the error, then pick the line that fixes it.
Round 1 of 3
Sort the array of customer names from A to Z.
Error
error: no suitable method found for sort(String[])
method Collections.<T#1>sort(List<T#1>) is not applicable
(cannot infer type-variable(s) T#1
(argument mismatch; String[] cannot be converted to List<T#1>))Next step
Check your understanding
12 quick questions