Iterators(Computer Science > Java Program ) Questions and Answers
What is the output of this program?
import java.util.*;
class Collection_iterators {
public static void main(String args[]) {
LinkedList list = new LinkedList();
list.add(new Integer(2));
list.add(new Integer(8));
list.add(new Integer(5));
list.add(new Integer(1));
Iterator i = list.iterator();
Collections.reverse(list);
Collections.shuffle(list);
i.next();
i.remove();
while(i.hasNext())
System.out.print(i.next() + " ");
}
}
Explanation:-
Answer: Option B. -> 2 1 8i.next() returns the next element in the iteration. i.remove() removes from the underlying
collection the last element returned by this iterator (optional operation). This method can
be called only once per call to next(). The behavior of an iterator is unspecified if the
underlying collection is modified while the iteration is in progress in any way other than
by calling this method.
Output:
$ javac Collection_iterators.java
$ java Collection_iterators
2 1 8
(output will be different on your system)
What is the output of this program?
import java.util.*;
class Collection_iterators {
public static void main(String args[]) {
LinkedList list = new LinkedList();
list.add(new Integer(2));
list.add(new Integer(8));
list.add(new Integer(5));
list.add(new Integer(1));
Iterator i = list.iterator();
Collections.reverse(list);
Collections.sort(list);
while(i.hasNext())
System.out.print(i.next() + " ");
}
}
Explanation:-
Answer: Option C. -> 1 2 5 8Collections.sort(list) sorts the given list, the list was 2->8->5->1 after sorting it
What is the output of this program?
import java.util.*;
class Collection_iterators {
public static void main(String args[]) {
LinkedList list = new LinkedList();
list.add(new Integer(2));
list.add(new Integer(8));
list.add(new Integer(5));
list.add(new Integer(1));
Iterator i = list.iterator();
Collections.reverse(list);
while(i.hasNext())
System.out.print(i.next() + " ");
}
}
Explanation:-
Answer: Option B. -> 1 5 8 2Collections.reverse(list) reverses the given list, the list was 2->8->5->1 after
Explanation:-
Answer: Option D. -> EMPTYNone.
Output:
$ javac Collection_iterators.java
$ java Collection_iterators
EMPTY