Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Set question

 
Mahmoud Kamal
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've modified one of the code samples in the K&B book (page 562) as a trial of seeing how the code results will be changed, although the results were so confusing for me.

import java.util.*;
class SetTest{
public static void main (String [] args){
boolean ba[] = new boolean[5];

Set s = new HashSet();

ba[0] = s.add("a");
ba[1] = s.add(new Integer(300));
ba[2] = s.add("b");
ba[3] = s.add(new Integer(300));
ba[4] = s.add(new Object);

for(int x=0; x<ba.length; x++)
System.out.print(ba[x] + " ");
System.out.println("\n");
for (Object o : s)
System.print(o + " ");
}
}

The result of the above code should be

true true true true true

Although the results came out as:

true true true false true

I am really confused why it considered new Integer(300) as a duplicate object taking in consideration that it is Integer which is > 127 ?!!

Thanks in advance for your time

[ November 11, 2007: Message edited by: Mahmoud Kamal ]
[ November 11, 2007: Message edited by: Mahmoud Kamal ]
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why it considered new Integer(300) as a duplicate object taking in consideration that it is Integer which is > 127

Integer's equals() is overriden to compare values, not refrences. Hence, two Integer objects with the same values are considered duplicates.
 
Mahmoud Kamal
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ahmed Yehia:

Integer's equals() is overriden to compare values, not refrences. Hence, two Integer objects with the same values are considered duplicates.


Thanks Ahmed for the clarification
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic