Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

hashset

 
swati cha
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • 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 ...
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • 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 ]
 
vijaya bharath
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • 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.
 
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!