Arrays ↔ Collections
Arrays.asList(a,b,c) → fixed-size List (no add/remove). new ArrayList<>(Arrays.asList(...)) → resizable. int[] → List<Integer> via stream().boxed(). List<Integer> → int[] via mapToInt(). new HashSet<>(list) to deduplicate. list.toArray(new T[0]) back to array.
Primitive arrays and collections do not convert implicitly, so it is boxing through a stream one way and toArray coming back.
How It Works
Java's split between primitive arrays and collections makes conversion patterns worth knowing cold. Arrays.asList(a, b, c) wraps elements in a fixed-size list. Reads and sets work, but add or remove throws UnsupportedOperationException; wrap it as new ArrayList<>(Arrays.asList(...)) for a resizable copy. Primitives need streams: int[] becomes List<Integer> via Arrays.stream(arr).boxed().collect(Collectors.toList()), and the reverse uses list.stream().mapToInt(Integer::intValue).toArray().
Deduplication drops out of new HashSet<>(list), and list.toArray(new T[0]) returns to array land for object types. The core gotcha: Arrays.asList on an int[] produces a one-element List<int[]> rather than a list of integers, because primitives cannot be generic type arguments.
Step-by-Step Visualization
Code
Tips & Gotchas
Practice Problems
- 1Contains Duplicate
- 2Intersection of Two Arrays
- 3Group Anagrams
- 4Top K Frequent Elements
About the Arrays Utility API Pattern
java.util.Arrays methods and array ↔ collection conversion patterns. These utilities handle sorting, searching, copying, filling, and bridging between primitive arrays and Java collections.
When you see 'subarray', 'contiguous', or 'in-place', think arrays. The key is reducing brute-force O(n²) to O(n) using sliding window, two pointers, or prefix sums.
Common Array Interview Problems
- Two Sum
- Best Time to Buy & Sell Stock
- Maximum Subarray
- Merge Intervals
- Product of Array Except Self
- Container With Most Water
Frequently Asked Questions
Why does Arrays.asList(myIntArray) not give me a list of integers?
Generics cannot hold primitives, so the compiler treats the entire int[] as a single element and returns List<int[]> of size one. Convert with Arrays.stream(myIntArray).boxed().collect(Collectors.toList()), or switch the source array to Integer[] if boxing up front is acceptable.
Why does adding to the result of Arrays.asList throw an exception?
Arrays.asList returns a fixed-size view backed by the original array, so structural changes like add and remove are unsupported, though set works and writes through to the array. Copy it into new ArrayList<>(...) whenever you need a genuinely mutable list.
What is the fastest way to deduplicate an array in Java?
Pour it into a HashSet. New HashSet<>(list) for objects, or a loop of set.add(x) for primitives, for O(n) average time at the cost of losing order. Use LinkedHashSet to keep insertion order, or Arrays.stream(arr).distinct() for a stream-based one-liner.