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().
Feed/

How do Java collections perform a linear search?

No cover

Channel

Computer science one

1 page

"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)."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.