• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Q12 from chapter 7 SCJP

 
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
import java.util.*;

public class Group extends HashSet<Person>
{
public static void main(String arg[])
{
Q12 g = new Q12();
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());
System.out.println("contents............"+g);
}
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;
}

}
ANSWER
F is correct. The problem here is in Group's add() method�it should have been
add(Person), since the class extends HashSet<Person>. So this doesn't compile.
Pop Quiz: What would happen if you fixed this code, changing add(Object) to
add(Person)? Try running the code to see if the results match what you thought.

now my problem is that when I have done the appropriate changes and then run it again the Total is coming to be 5.But how is it possible as it is a set and a set not allow the duplicate entries........???

According to me the size should be 3.....
Please guide me..
 
Bartender
Posts: 6663
5
MyEclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please use appropriate CODE tags.

So where is the Q12 class ? Lets assume its Group

To answer your question, heres a hint. How does java determine if two objects are equal ? How do you determine if 2 Person classes are equal ?
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic