Link to home
Start Free TrialLog in
Avatar of Jay Roy
Jay RoyFlag for United States of America

asked on

hashset uniquness

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
Avatar of for_yan
for_yan
Flag of United States of America image

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.


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
Avatar of Jay Roy

ASKER

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

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
So it remains to you to check if method .add(..) returned true or false
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial