aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes hashset Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "hashset" Watch "hashset" New topic
Author

hashset

swati cha
Ranch Hand

Joined: Jul 04, 2006
Posts: 40
Why thw output is like this ?

import java.util.*;
public class Question26 {
public static void main(String[] args){
Set s1 = new HashSet(3);
Set s2 = new HashSet(3);
s1.add("string 1");
s1.add(null);
s1.add("string 2");
s1.add(null);
s2.add("string 3");
s2.add(null);
s2.add("string 2");
s2.add(null);
s1.retainAll(s2);
System.out.println(s1);
}
}
o/p:
[null,string 2]

can any one explain ...
ahmed yehia
Ranch Hand

Joined: Apr 22, 2006
Posts: 424
This is because of the retainAll() which removes any element that is not contained in the specified collection.

s1.retainAll(s2); // remove any element from 's1' that is not contained in 's2'
[ October 03, 2007: Message edited by: Ahmed Yehia ]
vijaya bharath
Ranch Hand

Joined: Jun 10, 2005
Posts: 66
Hi swati,

Basically the set doesn't allow duplicate values. So when you add string1,null,string2,null,string3,null the set will contain null,string1,string3,string2(Remeber hashset does not guarantee the order). In your code both s1 and s2 contains only one null object.
That is why you have only one null int he result as it is there in s2 also.

Thanks,
vijaya.


Regards,<br />Vijaya Bharath.<br />SCJP1.4 <br />SCWCD5.0
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: hashset