1.自然排序中的元素对象,都必须实现了Comparable接口,否则会抛出异常,案例如下:
public class MySetTree { public static void main(String args[]){ TreeSet treeSet = new TreeSet(); treeSet.add(new SetTreeTest()); treeSet.add(new SetTreeTest()); treeSet.add(new SetTreeTest()); System.out.println(treeSet); } } class SetTreeTest{ }
修正后:
public class MySetTree { public static void main(String args[]){ TreeSet treeSet = new TreeSet(); treeSet.add(new SetTreeTest()); treeSet.add(new SetTreeTest()); treeSet.add(new SetTreeTest()); System.out.println(treeSet); } } class SetTreeTest implements Comparable{ @Override public int compareTo(Object o) { return 0; } }
2.由于TreeSet会调用元素的compareTo方法,这就要求所有元素的类型都相同,否则也会发生异常
public class MySetTree { public static void main(String args[]){ TreeSet treeSet = new TreeSet(); treeSet.add("1"); treeSet.add(0); System.out.println(treeSet); } }
3.当在TreeSet中放置null值时,会报空指针异常
public class MySetTree { public static void main(String args[]){ TreeSet treeSet = new TreeSet(); treeSet.add(null); System.out.println(treeSet); } }