Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Another Generics question

 
neha verma
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Refer to K&B book Q no 12- of Chapter 7-
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(Object 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; }
}
Here the answer is that code does not compile. I am not able to understand what is the problem with g.add(new Person("Hans"));
 
Manfred Klug
Ranch Hand
Posts: 377
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi neha,

compile it and look at which line the error occurs. Currently you are looking at the wrong part of the code.
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is in add() method, it should be add(Person o) instead of add(Object o) since Group's super class declaration was HashSet<Person>.
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even if you've solved that the code wouldn't work correct, because the class Person doesn't have a overridden equals method.

public boolean equals(Object obj) {}

So the duplicates aren't removed from the HashSet<Person>
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes and override hashCode also required, public int hashCode() {}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic