Reputation:
I know the output is four one three two. Can any one explain how? Since there are five items, but only four are printed.
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() + " " );
}
Upvotes: 1
Views: 387
Reputation: 7899
Set's doesn't allow duplicates .Where you are adding duplicate again like 'one' it is not being added .
TreeSet map = new TreeSet();
System.out.println(map.add("one"));
map.add("two");
map.add("three");
map.add("four");
System.out.println(map.add("one"));
Iterator it = map.iterator();
while (it.hasNext() )
{
System.out.print( it.next() + " " );
}
Result:
true
false
Second element didn't get added to the set .
While adding it checks if(e==null ? e2==null : e.equals(e2))
is true then only add element to Set
otherwise don't.
Upvotes: 1
Reputation: 1132
TreeSet is an Implementation of Set Interface
And Set always contain only unique elements
So even though you have put 5 elements the TreeSet actually contains only 4 since "one" is repeated twice.
Upvotes: 0
Reputation:
TreeSet does not allow duplicate entries. When it is accessed it will return elements in natural order (alphabetical order).
Refer: http://docs.oracle.com/javase/6/docs/api/java/util/TreeSet.html
Upvotes: 6