hashset uniquness

royjayd
royjayd used Ask the Experts™
on
hi guys

Have a simple question about  hashset uniquness. An  Arraylist can contain  duplicate objects while a hashset cannot contain duplicate objects. How does  the hashset determine the uniquness of an object?

thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Awarded 2011
Awarded 2011

Commented:
Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.
Awarded 2011
Awarded 2011

Commented:
The above quote is of course from the API:
http://download.oracle.com/javase/6/docs/api/java/util/HashSet.html
Awarded 2011
Awarded 2011

Commented:


This may be also interesting discussion though the answer to your question is mostly in the posts above:
http://www.coderanch.com/t/418129/java-programmer-SCJP/certification/HashSet-internal-working
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Author

Commented:
CustomerVO cus= new CustomerVO();
cus.setId("1");
Set set = new Hashset();
set.add(cus);
...

Later on in my code, i try to add the same cus object again
set.add(cus),

what error will  be thrown?

thx

Awarded 2011
Awarded 2011

Commented:
According to API above there will be no Exception but if objects are equal the method will
return false, and the set will be unchanged
Awarded 2011
Awarded 2011

Commented:
So it remains to you to check if method .add(..) returned true or false
Awarded 2011
Awarded 2011
Commented:
You probaly should also keep in mind that in order for it tow work properly if
CustomeVO is a custom class you need to override equals method of this class, so
it should know that if Id is the same  then objects are equal.
Don't know what will happen if you don't override, but it may not consider them identical - it is worth
experimenting.
But if you override then it should work as it is suuposed to work.
Mick BarryJava Developer
Top Expert 2010
Commented:
Have a read of the following, it gives a good explanation of how Sets work
http://download.oracle.com/javase/tutorial/collections/interfaces/set.html
HashSet uses hashCode to determine the bucket, and if there is collision on hashcode then, its uses object equality (equals method) of the element.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial