How do List.indexOf and List.contains decide whether an element matches, and why does overriding equals matter?
answer
- Matches via equals, not ==
- ArrayList calls o.equals(element)
- Default equals = identity → lookups fail
- Override equals AND hashCode
- indexOf first, lastIndexOf last, O(n)
basics
~20 sindexOf and contains find an element by comparing with equals, not by reference (==). For a custom class to be found, it must override equals correctly; otherwise the default equals compares object identity and lookups fail unless it is the exact same object.
solid answer
~40 sList.indexOf(o) returns the lowest index i where Objects.equals(o, get(i)) holds, and contains uses the same test. ArrayList and LinkedList scan in order calling o.equals(element), with a separate path where null matches null; an unmodifiable List.of list throws NullPointerException on a null search instead. So a lookup depends on the search argument's equals, normally the element type's, not on a plain ==. The default Object.equals is reference equality, so two distinct-but-logically-equal objects (e.g. two new Point(1,2)) will not be found. To make value-based lookup work you must override equals, and Object.equals's Javadoc calls it generally necessary to override hashCode too, even though ArrayList's indexOf does not hash. indexOf returns the first matching index or -1 and lastIndexOf the last; on ArrayList and LinkedList contains is indexOf(o) >= 0, and all three are O(n) linear scans.
code
java · 11 linesrecord Point(int x, int y) {} // auto equals/hashCode by components
List<Point> list = new ArrayList<>();
list.add(new Point(1, 2));
boolean found = list.contains(new Point(1, 2)); // true (value equals)
int idx = list.indexOf(new Point(1, 2)); // 0
int missing = list.indexOf(new Point(9, 9)); // -1
// Without a value-based equals (plain class using Object.equals),
// contains(new Point(1,2)) would be false.go deeper
Knows contains/indexOf use equals, so a custom class must override equals to be found, and indexOf returns -1 when absent.
Explains that ArrayList calls o.equals(element) with null handling, knows the override-equals-and-hashCode rule, and that lookups are O(n).
Discusses the full equals contract, why hashCode pairs with equals even though ArrayList's scan does not use it, and when to switch to a HashSet for membership.
Reasons about equality strategy across the codebase (value vs entity equality, records, immutability), API contracts, and performance/data-structure selection at scale.
## The two methods - `boolean contains(Object o)` — does the list hold an element equal to `o`? - `int indexOf(Object o)` — the index of the **first** element equal to `o`, or `-1` if none. `lastIndexOf(o)` returns the **last** such index. ## How matching is decided: equals, not == The `==` operator compares **references** (are these the very same object in memory). `equals` compares **logical value** *if the class defines it that way*. `indexOf`/`contains` use **equals**. `List.indexOf`'s Javadoc defines the result as the lowest index `i` such that `Objects.equals(o, get(i))`, and `ArrayList` and `LinkedList` implement it along these lines: ``` if (o == null) { for (int i = 0; i < size; i++) if (get(i) == null) return i; } else { for (int i = 0; i < size; i++) if (o.equals(get(i))) return i; } ``` Key points: it calls `o.equals(element)` (the **argument's** equals), and it handles `null` separately so searching for `null` works on these lists. Two limits on reading that as a rule for every `List`: - **The call itself is not promised.** `Collection`'s Javadoc says the specification should not be construed to imply that `o.equals(e)` is invoked, because implementations may avoid it, for example by comparing hash codes first. - **Not every list accepts a null search.** Lists from `List.of` (JDK 9) and `List.copyOf` (JDK 10) throw `NullPointerException` on `contains(null)` and `indexOf(null)`, while a `Stream.toList()` result permits null. ## Why overriding equals matters If your class does **not** override `equals`, it inherits `Object.equals`, which is just `==` (reference identity). Then: ``` class Point { int x, y; Point(int x,int y){this.x=x;this.y=y;} } List<Point> list = new ArrayList<>(); list.add(new Point(1, 2)); list.contains(new Point(1, 2)); // false! different object, default equals ``` The two `Point(1,2)` objects are logically equal but are different instances, so the default `equals` says they are not equal and the search fails. Override `equals` to compare fields: ``` @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Point p)) return false; return x == p.x && y == p.y; } @Override public int hashCode() { return Objects.hash(x, y); } ``` Now `contains(new Point(1,2))` returns `true`. ## The equals contract you must honor `equals` must be reflexive, symmetric, transitive, consistent, and `x.equals(null)` must be false. Also, `Object.equals`'s Javadoc says it is **generally necessary to override `hashCode`** whenever you override `equals`, because equal objects must have equal hash codes. `indexOf`/`contains` on `ArrayList` and `LinkedList` do not use `hashCode` (they scan linearly), but `HashSet`/`HashMap` do — so breaking that rule causes bugs elsewhere. Records (`record Point(int x, int y)`, final since JDK 16) generate a correct `equals`/`hashCode` for you automatically. ## Direction and cost - `indexOf` scans front-to-back, returns the **first** match. - `lastIndexOf` scans back-to-front, returns the **last** match. - All are **O(n)** linear scans (no index/hash on a plain `List`). For frequent membership tests on large data, prefer a `HashSet`. ## Combined with subList Because `subList` returns a real `List`, you can search just a range: `list.subList(from, to).indexOf(x)` returns the index **within the sub-view** (0-based from `fromIndex`), or -1. The same equals-based matching applies.
- Does indexOf on an ArrayList use hashCode?No. ArrayList does a linear equals-based scan and never calls hashCode. hashCode matters for hash-based collections like HashSet/HashMap. Collection's Javadoc does leave an implementation free to compare hash codes first, so this is a fact about ArrayList rather than about every List.
- What is the easiest correct way to get value-based equals/hashCode for a simple data class?Use a record: record Point(int x, int y) {} auto-generates equals, hashCode, and toString based on its components.
- Saying indexOf/contains use == (reference equality)
- Overriding equals but not hashCode
- Thinking List membership uses hashing like a HashSet
- Forgetting indexOf returns -1 (not throws) when absent
- Assuming null can never be searched for: ArrayList allows it, though a List.of list throws
- records
- Java 16pre-release 14
Assumes JDK 27. Lists from List.of (JDK 9) and List.copyOf (JDK 10) throw on a null search on both 27 and 25 LTS. Records, final in JDK 16, behave the same on both.
context
- List (Java SE 27 & JDK 27)docs.oracle.com
- Collection (Java SE 27 & JDK 27)docs.oracle.com
- Object (Java SE 27 & JDK 27)docs.oracle.com