SwadhyAI Notes

All Java notes

Java List

›Short versionOpen if you only have a minute.
  • A list is an ordered sequence. Duplicates are allowed, and elements have indexes starting at 0.
  • contains, remove(Object), and indexOf match elements with equals.
  • get and set are constant time on ArrayList and linear on LinkedList.
  • Inserting or removing at an index shifts every later ArrayList element.
  • subList is a live view of a range. Structural changes outside that view invalidate it.
  • The usual construction is List<E> items = new ArrayList<>().

A playlist, a line of search results, a log of events: each one is a sequence where position matters and the same value may appear twice. That is a . The is how you name a position. A is allowed because the contract is about order, not uniqueness.

Searching the sequence is a separate promise from jumping to a position. get uses the index. indexOf uses . Mixing those up is how a loop becomes accidental quadratic work.

What the interface guarantees

Order is insertion order until you sort or move elements yourself. add(e) appends. add(i, e) inserts and shifts the tail up. remove(i) closes the gap. set(i, e) replaces and does not change the size.

remove(Object) removes the first element that equals the argument. On a List<Integer>, remove(2) removes the element at index 2, because 2 is an int. Passing an Integer removes by equality. That overload is a classic source of off-by-one surprises.

A is how you hand someone a range without copying. Treat it as the same list seen through a window.

Position and equality

ListDemo.java
List<String> names = new ArrayList<>();
names.add("Ada");
names.add("Grace");
names.add("Ada");

names.get(1);            // "Grace", by index
names.indexOf("Ada");    // 0, first equals match
names.remove("Ada");     // drops index 0, not every Ada
names.subList(0, 1);     // a live view of what remains at the front

names contains Integer values 10 and 20. You write names.remove(10). What is removed, and why might that throw?

The argument is an int, so remove selects the index overload. Index 10 is past the end of a two-element list, and the call throws IndexOutOfBoundsException. To remove the value 10, pass Integer.valueOf(10) so equals is used.