TreeSet เป็นคลาสย่อยของ AbstractSet นำ NavigableSet Interface ไปใช้ ค่าเริ่มต้น เรียงจากน้อยไปมาก (Ascending) ใช้ Comparable เรียงลำดับ เพิ่มสมาชิกได้เฉพาะชนิดเดียวกัน มิฉะนั้นโยน ClassCastException
ไวยากรณ์คลาส
public class TreeSet<E> extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, Serializable
วนลูป TreeSet ได้ 2 วิธีหลัก
1. ใช้ Iterator
import java.util.*;
public class IteratingTreeSetTest {
public static void main(String[] args) {
Set<String> treeSet = new TreeSet<>();
treeSet.add("Ramesh");
treeSet.add("Adithya");
treeSet.add("Jai");
treeSet.add("Vamsi");
treeSet.add("Chaitanya");
Iterator<String> it = treeSet.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
Adithya
Chaitanya
Jai
Ramesh
Vamsi
2. ใช้ For-each Loop
import java.util.*;
public class IteratingTreeSetForEachTest {
public static void main(String[] args) {
Set<String> treeSet = new TreeSet<>();
treeSet.add("India");
treeSet.add("Australia");
treeSet.add("West Indies");
treeSet.add("South Africa");
treeSet.add("England");
for (String str : treeSet) {
System.out.println(str);
}
}
}
Australia
England
India
South Africa
West Indies
เพิ่มเติม: TreeSet รองรับ descendingIterator() สำหรับวนลูปย้อนกลับ (Descending) และ descendingSet() ได้ View เรียงจากมากไปน้อย