Concept
How do Java collections perform a linear search?
ComputerScienceOne / Searching
"Java Set and List collections provide several linear search methods. Both have a public boolean contains(Object o) method that returns true or false depending on whether or not an object matching o is in the collection. The List collection has an additional public int indexOf(Object o) method that returns the index of the first matched element and −1 if no such element is found (Sets are unordered and have no indices, so this method would not apply). All of these functions are equality-based and they do not take a Comparator object. Instead, the elements are compared using the object’s equals() (and possibly hashCode()) method. The first element x such that x.equals(o) returns true is the element that is determined to match. For this reason, it is important to override both of these methods when designing objects (see Section 36.3.3)."
Related Ideas
- Why are equals() and hashCode() important when searching and using sets?ComputerScienceOne · Importance of javaequals() and javahashCode() Methods
- How does Java perform binary searches on arrays and lists?ComputerScienceOne · Sorted Collections
- What is the general searching problem?ComputerScienceOne · Searching
- How do equals() and hashCode() define object equality in Java?ComputerScienceOne · Common Methods
- How do Java sets store unordered unique elements?ComputerScienceOne · Dynamic Data Structures
- What is the difference between Comparable and Comparator in Java?ComputerScienceOne · Comparators
- How do Java lists provide dynamic data structures?ComputerScienceOne · Dynamic Data Structures
- How does a Comparator determine the order of two elements?ComputerScienceOne · Comparators