Treeset is a subclass of the AbstractSet class and implements the NavigableSet interface. By default, Treeset provides ascending output and will use the Comparable interface to sort the set elements. In Treeset, we can add elements of the same type, otherwise ClassCastException may be generated, because by default TreeSet uses the Comparable interface .
public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable
We can iterate in two waysTreeSet
We can iterateTreeSet < /strong>UseIteratorInterface
import java.util.*; public class IteratingTreeSetTest { public static void main(String[] args) { Set<String> treeSetObj = new <strong>TreeSet</strong><String>(); treeSetObj.add("Ramesh"); treeSetObj.add("Adithya"); treeSetObj.add("Jai"); treeSetObj.add("Vamsi"); treeSetObj.add("Chaitanya"); <strong>Iterator<String></strong> it = treeSetObj.iterator(); // <strong>Iterator interface</strong> while (it.<strong>hasNext()</strong>) { System.out.println(<strong>it.next()</strong>); } } }
Adithya Chaitanya Jai Ramesh Vamsi
We can usefor-each IterationElements of TreeSet>Loop
import java.util.*; public class IteratingTreeSetForEachTest { public static void main(String[] args) { Set<String> treeSetObj = new <strong>TreeSet</strong><String>(); treeSetObj.add("India"); treeSetObj.add("Australia"); treeSetObj.add("West Indies"); treeSetObj.add("South Africa"); treeSetObj.add("England"); <strong>for</strong>(<strong>String str : treeSetObj</strong>) { <strong>// for-each loop</strong> System.out.println(str); } } }
Australia<strong> </strong>England India South Africa West Indies
The above is the detailed content of How many ways are there to iterate over a TreeSet in Java?. For more information, please follow other related articles on the PHP Chinese website!