Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Is the Point class's hashCode() method any good, or should I override it and write my own?

Is there any way to actually see the source code of standard java classes by the way? I'm making a hash table of points (HashSet<Point>) and I want to make sure that it will hash well, but I can't see what Point's hashCode() method actually looks like, so I don't know how good it really is. Can anyone help me? Should I override it? And if so, is there an easy way to do this without creating a whole new java file/class?

like image 816
Tim Avatar asked Feb 12 '12 19:02

Tim


2 Answers

If you're searching for the hashCode() of java.awt.Point, it is defined in java.awt.geom.Point2D.

/**
 * Returns the hashcode for this <code>Point2D</code>.
 * @return      a hash code for this <code>Point2D</code>.
 */
public int hashCode() {
    long bits = java.lang.Double.doubleToLongBits(getX());
    bits ^= java.lang.Double.doubleToLongBits(getY()) * 31;
    return (((int) bits) ^ ((int) (bits >> 32)));
}

Note that the question "Will it hash well?" is hard to answer, it depends primarily on usage pattern.

You can access the source code of nearly all "standard Java classes", just search for the src.zip file in your JDK installation directory (or use an IDE like Eclipse/NetBeans and click F3 on the class name).

like image 95
rlegendi Avatar answered Oct 13 '22 00:10

rlegendi


Is there any way to actually see the source code of standard java classes by the way?

Yes - I believe it usually comes with the JDK, in a src.zip file within your JDK directory. If it's not, then the way to get it will depend on the version of Java you're using. The full JDK 6 source is available here for example, or JDK 7 has a separate source code download page with various options.

As for how good the hash is - why not test it with a sample of your actual points? There will always be the possibility of collisions, but whether or not they really occur will depend on your data. One easy way of finding out how collision-free the hash is in your case is to use a Multiset from Guava - add the hash code from each point to the set, and then afterwards that will basically give you the frequency of each hash code.

To be honest, I'd expect the hash algorithm to be pretty reasonable for general purpose use. But testing is always a good idea if you're concerned.

like image 40
Jon Skeet Avatar answered Oct 13 '22 00:10

Jon Skeet