Note that there are some explanatory texts on larger screens.

plurals
  1. POguava-libraries: Is Objects.hashCode(Object[]) collision safe?
    text
    copied!<p>In looking at different options for overriding <code>hashCode()</code>, I was directed to <code>Objects.hashCode(Object[])</code> in Google's guava-libraries (<a href="http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Objects.html#hashCode%28java.lang.Object...%29" rel="nofollow" title="Objects.hashCode&#40;Object[]&#41; javadoc">javadoc</a>). The javadoc states that it delegates to <code>Arrays.hashCode(Object[])</code>. Is it safe to use this method in many different object types? Isn't this prone to hash collision, or is this not likely simply because containers usually only contain one type of object?</p> <p>As a simple example, consider the following classes,</p> <pre><code>public class Student { private final String name; public Student(String name) { this.name = name; } @Override public int hashCode() { return Objects.hashCode(name); } } public class Teacher { private final String name; public Teacher(String name) { this.name = name; } @Override public int hashCode() { return Objects.hashCode(name); } } public class HashCodeDriver { public static void main(String[] args) { final String name = "moe"; Student s = new Student(name); Teacher t = new Teacher(name); long studentHash = s.hashCode(); long teacherHash = t.hashCode(); System.out.println("studentHash=" + studentHash + " teacherHash=" + teacherHash); if(studentHash == teacherHash) { System.out.println("hash codes match"); } else { System.out.println("hash codes don't match"); } } } </code></pre> <p>Output:</p> <pre><code>studentHash=108322 teacherHash=108322 hash codes match </code></pre> <p>The objects are two different types but are generating the same hash code. Isn't this a problem? Should I pass in the class as the first parameter to prevent this collision? For example,</p> <pre><code>public class Student { private final String name; public Student(String name) { this.name = name; } @Override public int hashCode() { return Objects.hashCode(Student.class, name); } } public class Teacher { private final String name; public Teacher(String name) { this.name = name; } @Override public int hashCode() { return Objects.hashCode(Teacher.class, name); } } </code></pre> <p>Is this why the javadoc warns about only supplying a single object to this method? From the javadoc,</p> <blockquote> <p>Warning: When a single object is supplied, the returned hash code does not equal the hash code of that object.</p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload