The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics K&B doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics K&B doubt" Watch "Generics K&B doubt" New topic

Generics K&B doubt

deep rai
Ranch Hand

Joined: Oct 04, 2007
Posts: 56
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;}

which of the following occur atleast once when the code is compiled & run?
a) adding Hans
b) adding Lotte
c) adding Jane
d) Total:3
e) Total:5
f) The code does not compile
g) An exception is thrown at runtime

Answer :F

can you explain me why ?
ahmed yehia
Ranch Hand

Joined: Apr 22, 2006
Posts: 424
return super.add(o);
Here where it breaks..

This is because you are attepmting to add objects of type 'Object' to the hashSet which is orignally declared to take only objects of type 'Person'. If you change the parameter of the add() to take 'Person' the code will compile fine. eg:

public boolean add(Person o)
deep rai
Ranch Hand

Joined: Oct 04, 2007
Posts: 56
ok thanks Ahmed
I agree. Here's the link: http://aspose.com/file-tools
subject: Generics K&B doubt
Similar Threads
A Generics and Collections Problem
Generic Doubt
Another Generics question
what is the correct answer?
K&B Self Test Pg 617, Q12- HashSet doubt