Reputation: 75
I am a new learner of java. I have overridden equals
and hashcode
for my Animal class. I would expect that, using a HashSet<Animal>
as below, only one Animal
will be inserted into the HashSet
. However the second Animal
object is getting added to the set despite having the same properties. Can anyone look into it?
import java.util.*;
class SetTest
{
public static void main(String [] args)
{
Set<Animal>s=new HashSet<Animal>();
Animal a=new Animal(2);
boolean b1=s.add(a);
System.out.println("hi "+b1);
Animal b=new Animal(2);
boolean b2=s.add(b);
System.out.println("hi "+b2);
}
}
class Animal
{
int t;
Animal(int a)
{
t=a;
}
public boolean equals(Object O)
{
if(O instanceof Animal && ((Animal)O).t==t)
return true;
return false;
}
public int hashcode()
{
return t;
}
}
Output: hi true hi true
Thanks a Lot.
Upvotes: 1
Views: 107
Reputation: 6119
Your code has a mistype hashcode: write hashCode not hashcode .
import java.util.*;
class SetTest {
public static void main(String [] args) {
Set<Animal>s=new HashSet<Animal>();
Animal a=new Animal(2);
boolean b1=s.add(a);
System.out.println("hi "+b1);
Animal b=new Animal(2);
boolean b2=s.add(b);
System.out.println("hi "+b2);
}
}
class Animal {
int t;
public Animal(int a) {
t=a;
}
@Override
public boolean equals(Object O) {
return O instanceof Animal
&& ((Animal)O).t==t;
}
@Override
public int hashCode() {
return t;
}
}
Upvotes: 1
Reputation: 300
Java uses hashCode and equals method to check if two objects are equal. HashSet internally uses HashMap. You can refer HashMap.put(K key, V value) method for more details.
Upvotes: 0
Reputation: 10004
If you are using eclipse, you can make use of the source code generator and there by avoiding the common human error(the like you did it over here. Right click on the class -> source -> generate hashcode and equals methods. which will pop up window. There you can choose the fields which you need to consider for equals(equality of object) and hashcode generation.
Upvotes: 0
Reputation: 691685
You didn't override hashCode()
. You introduced another method called hashcode()
. Case matters.
When your intention is to override a method, always use the @Override annotation:
@Override
public int hashcode()
If you had done that, the compiler would have noticed the typo and have refused to compile the class.
Upvotes: 7