aspose file tools*
The moose likes Beginning Java and the fly likes  Set Does not allow Duplicate Element Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark " Set Does not allow Duplicate Element " Watch " Set Does not allow Duplicate Element " New topic
Author

Set Does not allow Duplicate Element

Deepak Sahu
Greenhorn

Joined: Dec 08, 2009
Posts: 19
Hi ,


Can any one provide the answer for "Why Set Does not allow duplicate elements".
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

What do you think why it's not allowed?


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

I will put it in other way,

Why List allows duplicate elements ? and do you know the meaning of Abstract Data Type(ADT)?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19720
    
  20

The simple answer: because that's the definition of a set, in just about any context including math and programming.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11419
    
  16

Because sometimes you need a collection that doesn't allow duplicate elements, and you have to give it some kind of name.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Nico Van Brandt
Ranch Hand

Joined: Mar 31, 2011
Posts: 66

It's by design, so whatever you think... it's supposed to be that way


Oracle Java SE6 Certified Programmer
Oracle Java EE5 Certified Web Component Developer
Dave Brock
Greenhorn

Joined: Apr 14, 2011
Posts: 2

Unlike using a List, which can include duplicates, a Set does not. Take a look at the Java API definition of a Set:
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

As it says, that is the true definition of a set as in the math and science industries. You will often need a List for when you do not want duplicates and want things to be distinct.

If you want information on ADT for Java, this might help you:
http://css.freetonik.com/wiki/abstract_data_types_and_algorithms:basic_java_review
 
jQuery in Action, 2nd edition
 
subject: Set Does not allow Duplicate Element