Zum Hauptinhalt springen

Week 6 Day 1 — Collection, List, and ArrayList

Goal

Today I want the collection type tree and a default list I can defend in an interview.

Main questions:

  1. What is a Collection vs Collections vs Map?
  2. What does the List contract add?
  3. ArrayList vs LinkedList vs array?
  4. When do I copy vs wrap?
  5. How do lists show up in Spring APIs?

1. Three names that are not the same

NameWhat it is
Collection<E>Interface: a group of elements. List, Set, Queue extend it.
CollectionsUtility class: unmodifiableList, sort, emptyList.
Map<K,V>Not a Collection. A set of key–value entries. keySet() / values() / entrySet() are collections.

Iterable
└── Collection
├── List (ordered, duplicates, index)
├── Set (no duplicates)
└── Queue (offer / poll)
Map (separate)

Memory sentence:

Collection is the interface. Collections is the helper class. Map is not a Collection.


2. The List contract

A List is ordered and allows duplicates. Positions matter: get(i), add(i, e), indexOf.


List<String> names = new ArrayList<>();
names.add("Ada");
names.add("Ada"); // two entries
names.get(0); // "Ada"
names.set(0, "Bob");

equals on two lists is pairwise: same size, same elements in the same order (equals on each pair). A List is not a Set.

Null elements: ArrayList allows them. I still avoid null in lists I own; Optional and empty lists are clearer (Week 5).


3. ArrayList vs LinkedList vs array

ArrayList is a resizable array.

  • get / set by index: O(1)
  • append at the end: amortized O(1)
  • insert or remove at the front or middle: O(n) — elements must shift
  • extra capacity is one contiguous block (plus the list object)

LinkedList is a doubly linked list (and a Deque).

  • insert/remove at a known node: O(1)
  • get(i): O(n) — it walks
  • each element is a node object: more allocations, worse cache behavior

On a modern JVM, “LinkedList is faster for inserts” is almost always false unless I already hold the iterator at the insert point. The default list is ArrayList.

Array (Order[]): fixed length, length is a field, can hold primitives (int[]) without boxing. Use internally for tight loops. As a public API I prefer List<Order>.

Memory sentence:

Default to ArrayList. Linked lists rarely win in real JVMs.


4. Wrapping, copying, factory lists


List<Order> copy = new ArrayList<>(existing); // independent copy
List<Order> view = Collections.unmodifiableList(existing); // still sees mutations of existing
List<Order> of = List.of(a, b); // unmodifiable, rejects null

List.of and List.copyOf (Java 9+) are unmodifiable. add throws UnsupportedOperationException. They are not ArrayList. Do not cast them.

Arrays.asList(array) is a fixed-size view of the array. set is allowed. add is not. Changing the array changes the list.


5. Spring connection

  • Controller methods often bind JSON arrays to List<CreateLineRequest>.
  • @OneToMany bags: JPA can use List (ordered, bag/list semantics) or Set. Duplicates and equals on entities matter (Day 2–3).
  • JdbcTemplate.query returns List<T>. Empty list means no rows, not null.
  • Do not return a live Hibernate persistent list from a closed session without copying — LazyInitializationException is a later JPA topic; the Java idea is: do not leak a collection I do not own.

6. Common traps

Trap 1: Collection vs Collections mix-up.

Trap 2:LinkedList for lots of inserts” without an iterator at the position.

Trap 3: Arrays.asList then add. UnsupportedOperationException.

Trap 4: Casting List.of(...) to ArrayList.

Trap 5: Returning null instead of List.of() from a repository-style method.


Practice Questions and Answers

Question 1

Is Map a Collection?

Answer:

No. Map is a separate interface. Its keySet, values, and entrySet views are collections. I iterate a map through those views, not as a Collection of pairs unless I use entrySet.


Question 2

ArrayList vs LinkedList?

Answer:

ArrayList is a resizable array: O(1) index access, cheap append, O(n) middle insert. LinkedList is nodes: cheap insert only at a known node, O(n) index access, more garbage. I default to ArrayList. I use LinkedList only when I need Deque operations and have measured a win — which is rare.


Question 3

What does List.of("a", "b") give me?

Answer:

An unmodifiable list of two non-null elements. add / remove throw. It is not an ArrayList. Nulls are rejected.


Question 4

Why is array.length a field and list.size() a method?

Answer:

An array’s length is part of the object header/layout and cannot change. A List is an interface; size is computed or stored by the implementation and can change, so it is a method.


Question 5

When do I copy a list Spring or JPA gave me?

Answer:

When I need a snapshot that survives the persistence context or a request, or when I must not expose a live mutable view. List.copyOf or new ArrayList<>(source) depending on whether I want unmodifiable vs a mutable copy I own.


Memory sentences

Collection is the interface. Collections is the helper. Map is not a Collection.

Default to ArrayList; linked lists rarely win in real JVMs.

Empty means List.of(), not null.

Next: Week 6 Day 2 — Set and Map Contracts