File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Set question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Set question" Watch "Set question" New topic
Author

Set question

Mahmoud Kamal
Greenhorn

Joined: Oct 22, 2007
Posts: 5
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

Joined: Apr 22, 2006
Posts: 424
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

Joined: Oct 22, 2007
Posts: 5
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Set question