Reputation: 57
Why is the output of this program false
? I am expecting true
as n object initialize with same string what I am checking for.
public class Test {
public static void main(String[] args) {
Name n = new Name("jyoti", "meher");
Set<Name> s = new HashSet();
s.add(n);
System.out.println(s.contains(new Name("jyoti", "meher")));
}
}
class Name {
String name, title;
public Name(String name, String title) {
this.name = name;
this.title = title;
}
public boolean equals(Object o) {
if (!(o instanceof Name)) {
return false;
}
Name n = (Name) o;
return n.name.equals(name) && n.title.equals(title);
}
}
Upvotes: 2
Views: 161
Reputation: 1372
To get the correct output true you need to override the hashCode() method in the Name Class
Upvotes: 4
Reputation: 7
In the Name class both equal and hashcode method should override.so that output will be true.
Upvotes: 1
Reputation: 1157
You should override equals() and hashcode() method to ensure the contract is satisfied to use your object as a key in the implementations like HashSet and HashMap.
You have overridden equals correctly. You can override hashcode also like below
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((name == null) ? 0 : name.hashCode());
result = prime * result + id;
result = prime * result
+ ((title == null) ? 0 : title.hashCode());
return result;
}
Overriding hashcode facilitates your object to be stored in different slots based on the hashcode which makes your search faster.
Hope this helps
Upvotes: 0
Reputation: 1260
If two objects have different hashCode values then they will be considered not equal by a HashSet
.
Whenever you override equals you should also override hashCode()
to ensure it is consistent. This is particularly important when dealing with HashSet
and HashMap
which rely on the hash code to distribute objects.
You can make your code work with the following (non-optimal) implementation of hashCode:
@Override
public int hashCode() {
return 1;
}
This will force the HashSet
to use your equals()
method when comparing your Name
objects. If you used both name
and title
when generating the hash code then there would be less occasions when the equals method would have to be used.
Upvotes: 2