Bifalgorithm post · Computer science one · Searching
How do Java collections perform a linear search?
How do Java collections perform a linear search? (Computer science one · Searching) — "Java Set and List collections provide several linear search methods. Bot…
Ideas in this flowchart
- Java Set and List collections provide equality-based linear search methods.
- Both collections provide contains(Object o), which returns true when a matching object is present and false otherwise.
- List provides indexOf(Object o), which returns the index of the first matching element or −1 when none is found.
- This method does not apply to Set because sets are unordered and have no indices.
- All of these search functions compare elements by equality.
- The functions do not accept a Comparator object.
- Elements are compared using equals(), and possibly hashCode().
- The first element x for which x.equals(o) returns true is considered a match.
- Objects used with these collections should override both equals() and hashCode().