Java Reference
In-Depth Information
worst-case scenario, you need to search through 2,500 numbers. To keep your search process fast, you can increase
the number of buckets as the numbers in one bucket increases to a point where the time taken to search for a number
becomes a performance concern.
The hash-based collections in Java work similar to the collection of numbers that I discussed. Note that a Java
collection stores only objects. They do not allow storing of primitive type values. Two methods in the Object class are
central to the working of hash-based collections. Those methods are equals() and hashCode() .
Hash-based collections maintain a number of buckets to store objects. When you add an object to a hash-based
collection, Java gets the hash code value of the object by calling object's hashCode() method. Then, it applies an
algorithm to the hash code value to compute the bucket in which the object should be placed. When you want to
check if an object exists in a hash-based collection, Java applies the same logic to compute the bucket in which the
object might have been placed. It calls the hashCode() method of the object and applies some algorithm to compute
the bucket in which it might have been placed. Then, it uses the equals() method of the object to compare the object
with existing objects in the bucket to check if the object exists in that bucket.
The internal workings of the hash-based collections in Java sound easy. However, it is full of complications for
programmers if the hashCode() and equals() methods are not implemented correctly in the class whose objects are
stored in hash-based collections. Let's consider the code for a BadKey class, shown in Listing 12-34.
Listing 12-34. A BadKey Class That Is Not a Good Candidate for Keys in Hash-based Collections
// BadKey.java
package com.jdojo.collections;
public class BadKey {
private int id;
public BadKey(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
@Override
public int hashCode() {
// Return the value of id as its hash code value
return id;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
Search WWH ::




Custom Search