File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Set issue.

 
L. Wei
Ranch Hand
Posts: 37
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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!!!
 
ramesh maredu
Ranch Hand
Posts: 210
Eclipse IDE Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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".
 
Sumukh Deshpande
Ranch Hand
Posts: 87
Firefox Browser IntelliJ IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 210
Eclipse IDE Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 37
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see. thanks a lot
 
Sumukh Deshpande
Ranch Hand
Posts: 87
Firefox Browser IntelliJ IDE
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Ramesh for explanation!
 
Yaroslav Ashurin
Greenhorn
Posts: 22
Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic