A TreeSet เป็นคลาสย่อยของ AbstractSet คลาสและไม่อนุญาตให้องค์ประกอบที่ซ้ำกัน โดยค่าเริ่มต้น TreeSet เก็บองค์ประกอบในลำดับจากน้อยไปมาก ร และความเร็วในการดึงข้อมูลขององค์ประกอบจาก TreeSet นั้นเร็วขึ้น คลาส TreeSet ภายใน ใช้ TreeMap เพื่อจัดเก็บองค์ประกอบ . องค์ประกอบใน TreeSet จะถูกจัดเรียงตามการเรียงลำดับตามธรรมชาติ
เรายังสามารถบันทึกองค์ประกอบ เก็บไว้ใน TreeSet เป็นไฟล์โดยใช้ Arrays.asList() และส่งชุดนี้เป็นอาร์กิวเมนต์ไปยัง writeObject() วิธีการของ ObjectOutputStream ชั้นเรียน
ไวยากรณ์
public class TreeSet extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable
ตัวอย่าง
import java.util.*;
import java.io.*;
public class TreeSetTest {
public static void main(String args[]) {
try {
String elements[] = {"Raja", "Jai", "Adithya", "Chaitanya"};
Set<String> set = new TreeSet<String>(Arrays.asList(elements));
FileOutputStream fos = new FileOutputStream("set.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(set);
oos.close();
System.out.println("The elements of a Set saved to a File Sucessfully");
} catch(Exception e) {
System.out.println("Error Occurred : " + e.getMessage());
}
}
} ผลลัพธ์
The elements of a Set saved to a File Sucessfully