Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics K&B doubt

 
deep rai
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok thanks Ahmed
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic