Java Reference
In-Depth Information
In Chapter2 , Listing2-27 's Point classoverrides equals() butdoesnotoverride
hashCode() . I later presented a small code fragment that must be appended to
Point 's main() methodtodemonstratetheproblemofnotoverriding hashCode() .
I restate this problem here:
Although objects p1 and Point(10, 20) are logically equivalent, these objects
have different hash codes, resulting in each object referring to a different entry in the
hashmap. If an object is not stored (via put() ) in that entry, get() returns null.
Listing 5-20 modifies Listing 2-27 's Point class by declaring a hashCode()
method. This method uses the aforementioned algorithm to ensure that logically equi-
valent Point objects hash to the same entry.
Listing 5-20. Using a hashmap to count command-line arguments
import java.util.HashMap;
import java.util.Map;
class Point
{
private int x, y;
Point(int x, int y)
{
this.x = x;
this.y = y;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
@Override
public boolean equals(Object o)
{
if (!(o instanceof Point))
return false;
 
Search WWH ::




Custom Search