Java Programming - Objects and Collections - Discussion

8. 

What will be the output of the program?

TreeSet map = new TreeSet();
map.add("one");
map.add("two");
map.add("three");
map.add("four");
map.add("one");
Iterator it = map.iterator();
while (it.hasNext() ) 
{
    System.out.print( it.next() + " " );
}

[A]. one two three four
[B]. four three two one
[C]. four one three two
[D]. one two three four one

Answer: Option C

Explanation:

TreeSet assures no duplicate entries; also, when it is accessed it will return elements in natural order, which typically means alphabetical.


Stan said: (Apr 29, 2016)  
If TreeSet assures not duplication, then, we should have them printed in the natural order. In that case, it should be A.

Sushma said: (Jul 18, 2016)  
Will any one explain this question?

Gayan said: (Aug 25, 2016)  
TreeSet has no duplicates. So 4th answer give up when TreeSet uses it comes natural order, natural order mean alphabetical order. Then the Answer is 'C'.

Vivekanand Kumar said: (Apr 20, 2017)  
In alphabetical order 'f' comes first then after 'o' then 'th' (here t are two times so we will go to next character and nest character is h so) "three" will come first then last two will come. That's why the answer 3rd is correct.

Gowtham said: (Jun 10, 2020)  
Clarify it clearly.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.