Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in generics

 
Sonam Zam
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.util.*;
public class Group extends HashSet<Person>
{
public static void main(String[] args)
{
Group g = new Group();
g.add(new Person("Hans"));
g.add(new Person("Lotte"));
g.add(new Person("Jane"));
g.add(new Person("Hans"));
g.add(new Person("Jane"));
System.out.println("Total: " + g.size());
}
public boolean add(Person p)
{System.out.println("Adding: " + p);
return super.add(p);
}

}

class Person
{
private final String name;
public Person(String name) { this.name = name; }
public String toString() { return name; }


}

program gives size = 5!
why is this HashSet allowing duplicate values? is it something related to Comparable?
[ April 26, 2007: Message edited by: Sonam Zam ]
 
megha joshi
Ranch Hand
Posts: 206
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Yes you guessed right...its related to HashCode() and equals().

The class Person , doesn't override these two methods. Hence the default object HashCode() and equals() method are used. Default equals() method is same as (==) Comparision so , it returns false for each pair of different Person object instances. Default HashCode() returns distinct hashCode value for every Person object.

So to prevent duplicate entries of the Person objects having same name...we need to override the equals() and HashCode() methods in Person class, as below

public boolean equals(Object o){
if ( o instanceof Person && this.name == o.name)
return true;
else
return false;
}

public int hashCode(){

return name.hashCode();
}

Hope this helps...

[ April 26, 2007: Message edited by: megha joshi ]
[ April 26, 2007: Message edited by: megha joshi ]
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Megha,




If I correct that:


It will fail to give the desirable result in the following case:



However works in the case:




So finally let's change the equals() definition:





Regards,
cmbhatt
 
megha joshi
Ranch Hand
Posts: 206
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the correction. I forgot the cast...
 
Sonam Zam
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey thank you very much friends!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic