• 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

Set concept in Java of Collection

 
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,

Which method Set use for not allowing duplicates ? Please explain with example
 
Ranch Hand
Posts: 808
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
equals() method and hashCode() if it is HashSet.
Correct me if I am wrong.
 
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[pedantic]Set doesn't use any methods, it's just an interface[/pedantic]

Lukas is right and that's why if you override equals or hashCode, you should really override the other one as well. If you don't, you can get some very, very strange behaviour in your sets (and maps). Like being able to add something to a set or map, but never able to find out later on if it is in there.

You appear to have Sierra&Bates - read chapter 7 (Objective 6.2), it's excellent.
 
Dinesh Tahiliani
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You mean to say that set uses equals() mtd to compare the object and doesn't allow duplicates?
 
Jason Irwin
Ranch Hand
Posts: 327
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Exactly how a set decides it has a duplicate or not depends on what type of set you are talking about.

Hashed sets (HashSet, LinkedHashSet etc) will use hashCode and equals.
Sorted sets (TreeSet etc) does something else (0 on comparison and then an equals test I think; not found good documentation on the specifics and it's not in Sierra&Bates).
CrazyMonkeySet may do something different again.

This is all in Chapter 7.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic