File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark " Set Does not allow Duplicate Element " Watch " Set Does not allow Duplicate Element " New topic

Set Does not allow Duplicate Element

Deepak Sahu

Joined: Dec 08, 2009
Posts: 23
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

Joined: Oct 27, 2005
Posts: 20271

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

How To Ask Questions How To Answer Questions
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

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

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:
I agree. Here's the link:
subject: Set Does not allow Duplicate Element
It's not a secret anymore!