Java Reference
In-Depth Information
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.
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;