GeekInterview.com
  I am new, Sign me up!
 
GeekInterview.com  >  Interview Questions  >  J2EE  >  Core Java
Go To First  |  Previous Question  |  Next Question 
 Core Java  |  Question 424 of 502    Print  
import java.util.*;

public class SetEx {
private String str;

SetEx(String s) {
str = s
}

public static void main(String[] ar) {
Set s = new HashSet();
SetEx setEx = new SetEx("Java");
SetEx setEx1 = new SetEx("Java");
String str1 = new String("Java");
String str2 = new String("Java");
s.add(setEx);
s.add(setEx1);
s.add(str1);
s.add(str2);
System.out.println("No Of elements in the Set is " + s.size());
}

What is the result and how?

  
Total Answers and Comments: 3 Last Update: August 25, 2009     Asked by: moorthimahalingam 
  
 Sponsored Links

 
 Best Rated Answer

No best answer available. Please pick the good answer available or submit your answer.
October 25, 2007 04:20:49   #1  
psuresh1982 Member Since: September 2006   Contribution: 1027    

RE: import java.util.*;public class SetEx ...

The Result is 3.

Hashset does not allowed duplicates. Here str1 and str2 considered as a duplicate. So it will erase one of the element. So the result shows 3.


 
Is this answer useful? Yes | No
August 23, 2009 21:01:28   #2  
james.vinett Member Since: August 2009   Contribution: 4    

RE: import java.util.*;public class SetEx { private String str; SetEx(String s) { str = s } public static void main(String[] ar) { Set s = new HashSet(); SetEx setEx = new SetEx("Java"); SetEx setEx1 = new SetEx("Java
The result is 3 even though you would want it to be 2.You MUST override equals() and hashCode() for proper use of add in HashSet.
 
Is this answer useful? Yes | No
August 25, 2009 11:35:02   #3  
inthiyaj Member Since: May 2009   Contribution: 4    

RE: import java.util.*;public class SetEx { private String str; SetEx(String s) { str = s } public static void main(String[] ar) { Set s = new HashSet(); SetEx setEx = new SetEx("Java"); SetEx setEx1 = new SetEx("Java
It prints --->

No Of elements in the Set is 3


 
Is this answer useful? Yes | No


 
Go To Top


 Sponsored Links

 
About Us -  Privacy Policy -  Terms and Conditions -  Contact -  Ask Question -  Propose Category -  Site Updates 

Copyright © 2005 - 2009 GeekInterview.com. All Rights Reserved

Page copy protected against web site content infringement by Copyscape