wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in generics" Watch "Doubt in generics" New topic
Author

Doubt in generics

Sonam Zam
Greenhorn

Joined: Apr 18, 2007
Posts: 9
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

Joined: Feb 20, 2007
Posts: 206
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

Joined: Feb 28, 2007
Posts: 1707
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


cmbhatt
megha joshi
Ranch Hand

Joined: Feb 20, 2007
Posts: 206
Thanks for the correction. I forgot the cast...
Sonam Zam
Greenhorn

Joined: Apr 18, 2007
Posts: 9
Hey thank you very much friends!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt in generics
 
Similar Threads
Doubt Regarding HashSet
Another Generics question
K&B Chapter 7 Question # 12
K&B Self Test Pg 617, Q12- HashSet doubt