Which interfaces does Vector.elements() return, and how do instanceof tests evaluate?\n\nimport java.util.*;\nclass H {\n public static void main (String[] args) {\n Object x = new Vector().elements();\n System.out.print((x instanceof Enumeration) + ",");\n System.out.print((x instanceof Iterator) + ",");\n System.out.print(x instanceof ListIterator);\n }\n}

Difficulty: Easy

Correct Answer: Prints: true,false,false

Explanation:


Introduction / Context:
This tests knowledge of legacy collections vs. modern iterators. Vector.elements() returns an Enumeration, not an Iterator or ListIterator.


Given Data / Assumptions:

  • x = new Vector().elements() produces a legacy Enumeration.
  • The program checks three instanceof relations and prints their boolean results separated by commas.


Concept / Approach:
Enumeration pre-dates the Java Collections Framework. It is distinct from Iterator and ListIterator. Therefore, only the first check is true.


Step-by-Step Solution:
x instanceof Enumeration → true. x instanceof Iterator → false. x instanceof ListIterator → false. Printed line: true,false,false.


Verification / Alternative check:
Replace elements() with iterator() from a modern collection (e.g., new ArrayList().iterator()) and observe the changed results.


Why Other Options Are Wrong:
Any output claiming Iterator or ListIterator is true misunderstands the return type of elements().


Common Pitfalls:
Equating Enumeration with Iterator; forgetting that ListIterator is a specialized bidirectional iterator available via listIterator(), not iterator() or elements().


Final Answer:
Prints: true,false,false

More Questions from Objects and Collections

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion