It is concrete classes that extends AbstractSet<E> and implements NavigableSet<E>, Cloneable and Serializable interfaces. All elements added to treeset are ordered automatically using their natural ordering, or by a Comparator typically provided at sorted set creation time whether you follow order or not. It does not allows to added duplicate element to set.
The set's iterator will traverse the set in ascending element order. Several additional operations are provided to take advantage of the ordering.
package collection.demos;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<String> names=new TreeSet<String>();
names.add("abc");
names.add("rit");
names.add("rit");
names.add("rit");
names.add("swek");
names.add("trog");
names.add("npr");
names.add("nvn");
for (String name : names) {
System.out.println(name);
}
}
}
OUTPUT
abcnpr
nvn
rit
swek
trog
In the output of program, we get all elements in accending order and rit is displayed only once, So only one instance of rit is added to TreeSet
Comments