• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

hashset

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ...
 
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
 
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic