一个TreeSet中 是的一个子类AbstractSet 类,它不允许重复的元素。默认情况下,TreeSet中 存储在 元素升序奥德ř和检索速度的元件的出一个TreeSet更快。TreeSet类在内部 使用TreeMap来存储元素。TreeSet中的元素根据其自然顺序进行排序。
我们还可以使用Arrays.asList()方法将TreeSet中存储 的元素保存到文件中,并将此设置作为参数传递给ObjectOutputStream 类的writeObject() 方法。
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