Which interfaces does ArrayList.iterator() implement? Evaluate the instanceof results.\n\nimport java.util.*;\nclass I {\n public static void main (String[] args) {\n Object i = new ArrayList().iterator();\n System.out.print((i instanceof List) + ",");\n System.out.print((i instanceof Iterator) + ",");\n System.out.print(i instanceof ListIterator);\n }\n}

Difficulty: Easy

Correct Answer: Prints: false, true, false

Explanation:


Introduction / Context:
This question distinguishes between Iterator, ListIterator, and collection types. The object returned by new ArrayList().iterator() is an Iterator but not a List and not a ListIterator.


Given Data / Assumptions:

  • i holds the iterator returned from an empty ArrayList.
  • Three instanceof checks are printed as booleans.


Concept / Approach:
An Iterator is produced by iterator(). A ListIterator—which supports bidirectional traversal and index operations—is produced by listIterator(), not iterator(). Also, an iterator is not a collection, so it is not a List.


Step-by-Step Solution:
i instanceof List → false. i instanceof Iterator → true. i instanceof ListIterator → false. Output is false, true, false.


Verification / Alternative check:
Replace iterator() with listIterator() and the third check becomes true for many list implementations.


Why Other Options Are Wrong:
Any claim that List is true confuses data structures with iterators; claiming ListIterator is true ignores the specific method used.


Common Pitfalls:
Assuming all list iterators are bidirectional; forgetting distinct factory methods in the collections API.


Final Answer:
Prints: false, true, false

More Questions from Objects and Collections

Discussion & Comments

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