HashSet does not allow duplicate object. In the following
code how it is allow two same objects?
Is there any one to spot my error
?
/* b.add( g.add(new Person("Hans")));
b.add( g.add(new Person("Lotte")));
b.add( g.add(new Person("Jane")));
b.add( g.add(new Person("Hans")));
*/
import java.util.*;
public class Group extends HashSet<Person> {
public static void main(
String[] args) {
Group g = new Group () ;
List<Boolean> b = new ArrayList<Boolean>();
b.add( g.add(new Person("Hans")));
b.add( g.add(new Person("Lotte")));
b.add( g.add(new Person("Jane")));
b.add( g.add(new Person("Hans")));
b.add(g.add(new Person("Jane")));
System.out.println ("Total: " + g.size() );
Iterator c =b.iterator();
while(c.hasNext())
{
System.out.println (c.next());
}
}
public boolean add(Person o) {
System.out.println("Adding: " + o) ;
return super.add(o);
}
}
class Person {
private final String name;
public Person(String name) { this.name = name; }
public String toString() { return name; }
public boolean equals (Person p)
{
boolean
test = false;
if( (p !=null) &&( p instanceof Person))
{
if (p.name ==this.name)
{
test= true;
}
}
return test;
}
}
output :::
Adding: Hans
Adding: Lotte
Adding: Jane
Adding: Hans
Adding: Jane
Total: 5
true
true
true
true
true