wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Set issue. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Set issue." Watch "Set issue." New topic
Author

Set issue.

L. Wei
Ranch Hand

Joined: May 01, 2008
Posts: 37


I got the return as


Is it supposed to be caught by Java coz Set is not allow to have duplicated elements. The add() method adds the object reference into the Set. I can still use the reference of the object to change the object. If I change the class Test to



I will get the return as



Please help me to clarify it. Does java have a way to avoid it? Thanks a lot!!!


SCJP SE 6.0, SCWCD J2EE 5
ramesh maredu
Ranch Hand

Joined: Mar 15, 2008
Posts: 210

This is what java API says about Set.

"Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set".


SCJP 1.5 94%.
The greatest glory in living lies not in never falling, but in rising every time we fall.
Sumukh Deshpande
Ranch Hand

Joined: Feb 17, 2008
Posts: 87

hi ramesh!!
Will you please explain your comment in a greater detail?

"Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set"
ramesh maredu
Ranch Hand

Joined: Mar 15, 2008
Posts: 210

Java API says if we have any mutable object in Set, and if we modify that object in such a way that equals method is effected then Set behavior is not specified

Here Ele class object is mutable, initially the object of this class t3 is added to Set with value of x as 50,then its value is changed to 60, and the property x is used in equlas method so modification to x value will effect its behavior.
L. Wei
Ranch Hand

Joined: May 01, 2008
Posts: 37
I see. thanks a lot
Sumukh Deshpande
Ranch Hand

Joined: Feb 17, 2008
Posts: 87

Thanks a lot Ramesh for explanation!
Yaroslav Ashurin
Greenhorn

Joined: Apr 25, 2008
Posts: 20

Hey,

Thanks to Roota for clear explanation of the Set problem; I've asked same question in the Beginners forum here: http://www.coderanch.com/t/410931/java/java/Duplicates-Set , and now I got the picture.


SCJP 1.5
 
Consider Paul's rocket mass heater.
 
subject: Set issue.
 
Similar Threads
What's wrong with this code? Why I am able to add duplicates with this code.
Q on collections framework: iteration order
Why mutable elements of Sets?
hashmap with duplicate key.
Question on HashSet & LinkedHashSet