Search...
FAQs
Subscribe
Pie
FAQs
Recent topics
Flagged topics
Hot topics
Best topics
Search...
Search within Java in General
Search Coderanch
Advance search
Google search
Register / Login
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
Forum:
Java in General
HashSet: Allow Duplicates
Ruchika Kapoor
Greenhorn
Posts: 22
posted 15 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
Hi,
Please find the code as below:
class Source { private String name; public Source(String nm){ this.name=nm; } public String getName(){ return name; } public boolean equals(Object obj){ if(this==obj)return true; if(!(obj instanceof Source)) return false; Source obj1=(Source)obj; return ((obj1.name).equalsIgnoreCase(this.name)); } public int hashcode(){ return name.hashCode(); } } public class RemoveDuplicates { public static void main(String a[]){ HashSet<Source> set=new HashSet<Source>(); Source src1=new Source("AB"); Source src2=new Source("BC"); Source src3=new Source("AB"); set.add(src1); set.add(src2); set.add(src3); System.out.println("Set contains "+set.contains(new Source("AB"))); Iterator itr=set.iterator(); Source s; Integer i; while(itr.hasNext()){ s=(Source)itr.next(); System.out.println(s.getName()); } } }
Why am I able to add duplicate objects(AB), while
java
api says, set does not allow duplicates.
Please advice.
Thanks
Christophe Verré
Sheriff
Posts: 14691
16
I like...
posted 15 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
hash
C
ode
[My Blog]
All roads lead to JavaRanch
Ruchika Kapoor
Greenhorn
Posts: 22
posted 15 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
thanks Christophe !
Consider Paul's
rocket mass heater
.
reply
reply
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
effect of overriding equals on Sets?
Question about hashSet
Behind HashSet
Generics Compiler error
Hashset & overriding hashcode()
More...