This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
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 The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics K&B doubt" Watch "Generics K&B doubt" New topic
Author

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