给出两种形式,供参考,希望对你有帮助
import java.util.*;
public static void main(String[] args) {
TreeSet ts = new TreeSet(new Comparator(){ //通过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;
}
});
ts.add("abcd");
ts.add("de");
ts.add("dcg");
ts.add("nnmgd");
ts.add("n");
Iterator it = ts.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
/*
//自定义类实现Comarator接口,具备比较功能
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;
}
}*/
|