• Post Reply Bookmark Topic Watch Topic
  • New Topic

Adding in a Set  RSS feed

 
ishani sharma
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

At (2) the size of set remains 2 even though we have removed i2 from the set.Why???
Thanks in advance.
 
dennis deems
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On line 3, an Integer object is created with a value of 1, and a reference to that object is assigned to the variable i2.
On line 7, a new Integer object is created with a value of 47, and its reference is assigned to the variable i2.
When the call is made to remove i2 from the set, the contents of the set are unchanged because i2 no longer points to an element in the set.
 
gaurav gupta sitm
Ranch Hand
Posts: 47
Java Redhat Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
first that is the basis of this program you must to know that Integer is immutable

now you can see figure when 47 value pass it does not go to object that contains 1 value , it create new block of 47 means object in memory same as String work.
now when you used i2 in remove(i2) it refer to new object that contains value 47 but set has not 47 so it return null and nothing is removed from set .

i think this picture will help you.
answer.png
[Thumbnail for answer.png]
 
ishani sharma
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Dennis
Thanks Gaurav
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!