import java.util.*;
class TreeSetComparatorDemo
{
public static void main(String[] args)
{
//使用比较器来实现TreeSet集合按长度排序
TreeSet ts = new TreeSet(new StrLenComparator());
ts.add("aaaa");
ts.add("aaaddhhrwewe");
ts.add("aaaddads");
ts.add("aaadddf");
ts.add("aaaddaaaa");
ts.add("aaaddfd");
ts.add("aaadd");
Iterator it=ts.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
class StrLenComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=(String)o1;
String s2=(String)o2;
int num=(new Integer(s1.length()).compareTo(new Integer(s2.length())));
//如果长度一样,按字符串自然排序
if(num==0)
return s1.compareTo(s2);
return num;
}
}