Reputation: 3
I try to check two set and I need both result are TRUE but they are not. I don't know why one of result is return false. Please help me, many thanks.
class CollectionExample:
Set<String> set1 = new HashSet<>();
set1.add(new String("A"));
set1.add(new String("B"));
Set<String> set2 = new HashSet<>();
set2.add("A");
set2.add("B");
System.out.println("set1.equal(set2): "+ set1.equals(set2));
Set<Person1> set3 = new HashSet<>();
set3.add(new Person1("A", "1"));
set3.add(new Person1("B", "1"));
Set<Person1> set4 = new HashSet<>();
set4.add(new Person1("A", "1"));
set4.add(new Person1("B", "1"));
System.out.println("set3.equal(set4): "+ set3.equals(set4));
entity Person1:
public class Person1 {
String firstName;
String lastName;
public Person1(String firstName, String lastName) {
// TODO Auto-generated constructor stub
this.firstName = firstName;
this.lastName = lastName;
}
public String firstName() { return firstName;}
public String lastName() { return lastName;}
}
Result:
set1.equal(set2): true
set3.equal(set4): false
Upvotes: 0
Views: 1499
Reputation: 910
The issue is not because of the comparison of Set
but that of the Person
class.
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
But it is not necessary that if two objects have same
hashcode()
then the two objects areequals()
as well.
Even if the computed hashcode()
is the same, the objects are not equals()
.
This is because the equals()
method inherited from the Object
class compares the reference as well. Hence the output.
Upvotes: 0
Reputation: 14035
You need to override equals()
and hashCode()
in your Person
class. Them implementation of HashSet
uses those to determine if two Person
instances are equal; if you don't override them then you'll get the default Object
implementation in which two Person
instances are equal only if they are the exact same reference.
Upvotes: 1