aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Another Generics question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Another Generics question" Watch "Another Generics question" New topic
Author

Another Generics question

neha verma
Ranch Hand

Joined: Jun 17, 2007
Posts: 37
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"));


Neha Verma
Manfred Klug
Ranch Hand

Joined: Jun 04, 2007
Posts: 377
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

Joined: Apr 22, 2006
Posts: 424
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

Joined: Dec 28, 2006
Posts: 893
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>


Remko (My website)
SCJP 1.5, SCWCD 1.4, SCDJWS 1.4, SCBCD 1.5, ITIL(Manager), Prince2(Practitioner), Reading/ gaining experience for SCEA,
ahmed yehia
Ranch Hand

Joined: Apr 22, 2006
Posts: 424
Yes and override hashCode also required, public int hashCode() {}
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Another Generics question
 
Similar Threads
what is the correct answer?
HashSet
K&B Self Test Pg 617, Q12- HashSet doubt
A Generics and Collections Problem
Generics K&B doubt