I am unclear about use of hashcode and equals method in java.I have following query
First
If I Override only equals method all objects of value Fred are added though HashSet implements set interface,which cant take repeated values.
Second If i override both equals and hashcode only one object is added to HashSet.Why?
Third If I implement only equals in this case will removing one Fred object will remove all?
class Person
{
String name;
Person(String name) {
this.name=name;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Person))
{
return false;
}
Person p = (Person)obj;
return p.name.equals(this.name);
}
/*@Override
public int hashCode() {
return name.hashCode();
}*/
}
public class HashSetDemo {
/*
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<Person> s= new HashSet<Person>();
s.add(new Person("Fred"));
s.add(new Person("Fred"));
s.add(new Person("Fred"));
s.add(new Person("Fred1"));
for(Person a:s) {
System.out.println(a.name);
}
s.remove(new Person("Fred"));
System.out.println(s);
}
}