File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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


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("string 2");
s2.add("string 3");
s2.add("string 2");
[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.


Regards,<br />Vijaya Bharath.<br />SCJP1.4 <br />SCWCD5.0
I agree. Here's the link:
subject: hashset
It's not a secret anymore!