Confused with Java Hash Set!!!!!!!!!!?
-
2. public class WrappedString { 3. private String s; 4. public WrappedString(String s) { this.s = s; } 5. public static void main(String[] args) { 6. HashSet<Object> hs = new HashSet<Object>(); 7. WrappedString ws1 = new WrappedString("aardvark"); 8. WrappedString ws2 = new WrappedString("aardvark"); 9. String s1 = new String("aardvark"); 10. String s2 = new String("aardvark"); 11. hs.add(ws1); hs.add(ws2); hs.add(s1); hs.add(s2); 12. System.out.println(hs.size()); } } What is the result? A. 0 B. 1 C. 2 D. 3 E. 4 F. Compilation fails. G. An exception is thrown at runtime we say that Hash set stores the unique values.. so i thought the size would be 1 but the size is 3. how is this possible?? can nyne xplain in detail??
-
Answer:
HashSet uses equals method to compare two objects before adding them. Since in the above code the Object's class equals method is not overriden in the WrappedString class the Object's class equals method is called and it consider ws1 and ws2 as different references hence it adds ws1, ws2 and s1 into the HashSet.
Krithika at Yahoo! Answers Visit the source
Other answers
Vikas Srivastava
Related Q & A:
- What is Hash Table, how to create a hash table?Best solution by Stack Overflow
- How to do reverse lookup in a Hash?Best solution by reverse-hash-lookup.online-domain-tools.com
- Who was the coolest character in Dazed and Confused?Best solution by buzzfeed.com
- What's a hash check?Best solution by Yahoo! Answers
- Skype and very confused?Best solution by Yahoo! Answers
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
For every problem there is a solution! Proved by Solucija.
-
Got an issue and looking for advice?
-
Ask Solucija to search every corner of the Web for help.
-
Get workable solutions and helpful tips in a moment.
Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.