Java OCA OCP Practice Question 2735

Question

Given:

1. import java.util.*;  
2. public class Main {  
3.   public static void main(String[] args) {  
4.     Set<Shape> s = new HashSet<Shape>();  
5.     s.add(new Shape(3));  s.add(new Shape(4)); s.add(new Shape(4));  
6.     s.add(new Shape(5));  s.add(new Shape(6));  
7.     s = null;  /*from w  ww  .  j a v  a 2s.c  om*/
8.     // do more stuff  
9.   }  
10. }  
11. class Shape {   
12.   int value;   
13.   Shape(int v) { value = v; }  
14. } 

When line 8 is reached, how many objects are eligible for garbage collection?

  • A. 4
  • B. 5
  • C. 6
  • D. 8
  • E. 10
  • F. 12


C is correct.

Note

Because Shape doesn't override equals(), there are five objects in the HashSet, plus the HashSet is also an object.

The int primitive associated with each Shape object is not an object.

Note: Even if equals() was overridden, six objects would be eligible.

The duplicate Shape object, while not in the Set, would still be eligible.




PreviousNext

Related