Reputation: 59
I am new in Collection
, as per my knowledge I have already override the hashCode()
and Equals()
method in Data
class, but when I trying to search the element it is giving "not found". Why? Please look at the code below aand help me to find the bug.
import java.util.*;
public class WordCounter {
public static void main(String args[]) {
HashSet<Data> set=new HashSet<Data>();
set.add(new Data("this",2));
set.add(new Data("that",3));
set.add(new Data("which",6));
set.add(new Data("how",7));
System.out.println(new Data("how",7).hashCode());
set.add(new Data("hey",3));
set.add(new Data("me",5));
Iterator<Data> itr=set.iterator();
while(itr.hasNext()) {
Data d=itr.next();
d.display();
}
Data e=new Data("how",7);
System.out.println(e.hashCode()+"\t");
if(set.contains(e))
System.out.println("found");
else
System.out.println("not found");
}
}
Data Class:
class Data {
String word;
int fre;
public Data(String w,int f) {
word=w;
fre=f;
}
public void display() {
System.out.println(word+"\t"+fre);
}
public boolean equals(Data e) {
return this.word.equals(e.word) && this.fre == e.fre;
}
public int hashCode() {
return this.word.hashCode() + this.fre;
}
}
Upvotes: 2
Views: 114
Reputation: 1414
You equals()
method is not used, because it has wrong signature. The correct signature is public boolean equals(Object o){ /* ... */ }
. Because the signatures don't match, you are effectively overloading the method instead of overriding. The working equals()
example:
@Override
public boolean equals(Object e)
{
if(!(e instanceof Data)){
return false;
}
Data d = (Data)e;
return this.word.equals(d.word) && this.fre == d.fre;
}
When overriding a method, use the @Override
annotation - then the code fails to compile if the signatures don't match, thus:
@Override
public boolean equals(Data d){ ... }
Will give you an error and save some debugging time. Also check out this question.
Upvotes: 1
Reputation: 4859
Perhaps your equals method is not used?
The signature is
public boolean equals(Object obj);
And it appears you have
public boolean equals(Data e);
Consider adding @Override
annotations when you want to override a parent method (in this case java.lang.Object)
Update
Changing your method to this solves the case.
public boolean equals(Object d) {
Data e = (Data) d;
return this.word.equals(e.word) && this.fre == e.fre;
}
Upvotes: 6