/** This student object has the hashcode overridden to be the perm, but the .equals checks both the perm and the name. As an exercise: is this a legal design? Or does it "violate the contract" of the hashCode and equals methods? (See Chapter 16 in HFH 2nd edition) */ public class Student { private String name; private int perm; public Student(String name, int perm) { this.name = name; this.perm = perm; } public String getName() { return name; } public int getPerm() { return perm; } public boolean equals(Object o) { if ( o == null) return false; if ( ! (o instanceof Student)) return false; Student s = (Student) o; return s.getPerm() == this.getPerm() && s.getName().equals(this.getName()); } public int hashCode() { return perm; } public static void main(String [] args) { Student s1 = new Student("Fred",1234567); Student s2 = new Student("Mary",1234567); Student s3 = new Student("Mary",1234567); Student s4 = s1; System.out.printf(" s1==s2: %b\n",s1==s2); System.out.printf("s1.equals(s2): %b\n",s1.equals(s2)); System.out.printf(" s1==s3: %b\n",s1==s3); System.out.printf("s1.equals(s3): %b\n",s1.equals(s3)); System.out.printf(" s1==s4: %b\n",s1==s4); System.out.printf("s1.equals(s4): %b\n",s1.equals(s4)); System.out.printf("System.identityHashCode(s1)=%d\n",System.identityHashCode(s1)); System.out.printf("System.identityHashCode(s2)=%d\n",System.identityHashCode(s2)); System.out.printf("System.identityHashCode(s3)=%d\n",System.identityHashCode(s3)); System.out.printf("System.identityHashCode(s4)=%d\n",System.identityHashCode(s4)); System.out.printf("s1.hashCode()=%d\n",s1.hashCode()); System.out.printf("s2.hashCode()=%d\n",s2.hashCode()); System.out.printf("s3.hashCode()=%d\n",s3.hashCode()); System.out.printf("s4.hashCode()=%d\n",s4.hashCode()); } }