Java OCA OCP Practice Question 2935

Question

Given:

2. import java.util.*;  
3. public class Main {  
4.   String name;  // w w  w. ja v a2 s.co  m
5.   Main(String s) { name = s; }  
6.   public static void main(String[] args) {  
7.     Set<Main> ms = new HashSet<Main>();      
8.     ms.add(new Main("Bob"));  
9.     System.out.print(ms + " ");  
10.     ms.add(new Main("Bob"));  
11.     System.out.print(ms + " ");  
12.     ms.add(new Main("Eden"));  
13.     System.out.print(ms + " ");  
14.   }  
15.   public String toString() { return name; }  
16. } 

What is the most likely result?

  • A. Compilation fails.
  • B. [Bob] [Bob] [Eden, Bob]
  • C. [Bob] [Bob] [Eden, Bob, Bob]
  • D. [Bob], followed by an exception.
  • E. [Bob] [Bob, Bob] [Eden, Bob, Bob]


E is correct.

Note

The Main class doesn't override equals(), so the two "Bob" instances are NOT seen as equal when added to the HashSet.




PreviousNext

Related