• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Set question  RSS feed

 
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 ]
 
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
Boost this thread!