import java.util.*;/**练习:按照字符串长度排序字符本身具备比较性,但是现在以字符的长度作为比较项*/class TreeSetTest{ public static void main(String[]args){ TreeSet ts = new TreeSet(new MyComparator()); ts.add("abc"); ts.add("c"); ts.add("da"); ts.add("adsfc"); ts.add("sdaw"); ts.add("amk2"); //迭代器取出 Iterator it = ts.iterator(); while(it.hasNext()){ System.out.println(it.next()); } }}//自定义比较器,继承Comparator()接口class MyComparator implements Comparator{ public int compare(Object o1,Object o2){ String s1 = (String)o1; String s2 = (String)o2; int num = s1.length() - s2.length(); //判断字符串长度相同时,根据字典顺序排 if(num == 0){ return s1.compareTo(s2); } else return num; } }