I'm working on deeper understanding of Java and I was experimenting with comparing the same objects.
I have created two string objects with the same value, but assigned to different variable. It turned out that they have the same hash codes.
After that I have created simple class representing person and created two instances of this class with the same parameters passed to constructor. It turned out that they have different hash codes.
Now I'm confused how does it work. Could you please explain me that?
my code:
public static class Person {
public String name;
public String lastName;
public Person(String name, String lastName) {
this.name = name;
this.lastName = lastName;
}
}
public static void main(String[] args) {
String s1 = new String("foo");
String s2 = new String("foo");
System.out.println("String1 hashcode: " + s1.hashCode());
System.out.println("String2 hashcode: " + s2.hashCode());
System.out.println("Is String1 equal to String2?: " + s1.equals(s2));
Person p1 = new Person("John", "Doe");
Person p2 = new Person("John", "Doe");
System.out.println("Person1 hashcode: " + p1.hashCode());
System.out.println("Person2 hashcode: " + p2.hashCode());
System.out.println("Is Person1 equal to Person2?: " + p1.equals(p2));
}
}
my output:
String1 hashcode: 101574
String2 hashcode: 101574
Is String1 equal to String2?: true
Person1 hashcode: 325040804
Person2 hashcode: 1173230247
Is Person1 equal to Person2?: false