A friendly place for programming greenhorns!
Big Moose Saloon
Search
|
Java FAQ
|
Recent Topics
Register / Login
Win a copy of
Arduino in Action
this week in the
General Computing
forum!
A special promo:
Enter your blog post or vote on a blogger to be featured in an upcoming Journal
JavaRanch
»
Java Forums
»
Certification
»
Programmer Certification (SCJP/OCPJP)
Author
Question on HashSet
wong sheena
Greenhorn
Joined: Apr 07, 2007
Posts: 23
posted
Apr 30, 2007 21:12:00
0
import java.util.*; public class Group extends HashSet <Person>{ public static void main(String args[]){ Group g = new Group(); g.add(new Person("Hana")); g.add(new Person("Lotte")); g.add(new Person("Jane")); g.add(new Person("Hana")); g.add(new Person("Jane")); System.out.println("Total "+g.size()); for(Person buffer:g) System.out.println(buffer); } public boolean add(Person o){ System.out.println("Adding:"+o); return super.add(o); } } class Person{ private String name; Person(String name){ this.name =name; } public String toString(){ return name; } public boolean equals(Object o){ if((o instanceof Person)&&(this.name==((Person)o).name)) return true; else return false; } public int harshCode() { return 4; } }
This is a Question from K & B pg 630.
I'm wondering why duplicate entry is allowed.
At first I thought it is because of the equals() and hashCode().I have added as well. Have I left out something??
Thanks in advance!
Meena R. Krishnan
Ranch Hand
Joined: Aug 13, 2006
Posts: 178
posted
Apr 30, 2007 21:34:00
0
First, change harshCode() to hashcode().
Then print out the returns of add() to see the duplicate ones are failing.
System.out.println(g.add(new Person("Hana"))); System.out.println(g.add(new Person("Lotte"))); System.out.println(g.add(new Person("Jane"))); System.out.println(g.add(new Person("Hana"))); System.out.println(g.add(new Person("Jane")));
I get the following result:
Adding:Hana true Adding:Lotte true Adding:Jane true Adding:Hana false Adding:Jane false Total 3 Jane Lotte Hana
wong sheena
Greenhorn
Joined: Apr 07, 2007
Posts: 23
posted
Apr 30, 2007 21:49:00
0
First, change harshCode() to hashcode().
YeaH should be hashCode(). hehe.. Thanks
I agree. Here's the link:
http://ej-technologies/jprofiler
- if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
subject: Question on HashSet
Similar Threads
K&B Chapter 7 Question # 12
Correctly override equals and hashcode
A Generics and Collections Problem
Another Generics question
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter