What is the result?

Given:
<code>
import java.util.*;
public class StringApp {
public static void main (String [] args) {
Set <String> set = new TreeSet <> ();
set.add(“X”);
set.add(“Y”);
set.add(“X”);
set.add(“Y”);
set.add(“X”);
Iterator <String> it = set.iterator ();
int count = 0;
while (it.hasNext()) {
switch (it.next()){
case “X”:
System.out.print(“X “);
break;
case “Y”:
System.out.print(“Y “);
break;
}
count++;
}
System.out.println (“\ncount = ” + count);
}
</code>
What is the result?

Given:

import java.util.*;
public class StringApp {
public static void main (String [] args) {
Set <String> set = new TreeSet <> ();
set.add("X");
set.add("Y");
set.add("X");
set.add("Y");
set.add("X");
Iterator <String> it = set.iterator ();
int count = 0;
while (it.hasNext()) {
switch (it.next()){
case "X":
System.out.print("X ");
break;
case "Y":
System.out.print("Y ");
break;
}
count++;
}
System.out.println ("\ncount = " + count);
}

What is the result?

A.
X X Y X Y
count = 5

B.
X Y X Y
count = 4

C.
X Y
count = s

D.
X Y
count = 2

Explanation:
A set is a collection that contains no duplicate elements. So set will include only two
elements at the start of while loop. The while loop will execute once for each element. Each
element will be printed.
Note:
*public interface Iterator
An iterator over a collection. Iterator takes the place of Enumeration in the Java collections
framework. Iterators differ from enumerations in two ways:
Iterators allow the caller to remove elements from the underlying collection during the iteration with
well-defined semantics.
Method names have been improved.
*hasNext
public boolean hasNext()
Returns true if the iteration has more elements. (In other words, returns true if next would return an
element rather than throwing an exception.)
*next
publicObjectnext()
Returns the next element in the iteration.



Leave a Reply 1

Your email address will not be published. Required fields are marked *