/*
练习:按照字符串长度进行排序。
*/
import java.util.*;
class TreeSetTest3
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet(new StrLenComparator());
ts.add("acd");
ts.add("fkif");
ts.add("dahahaha");
ts.add("xixix");
ts.add("ccc");
for (Iterator it = ts.iterator();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;
}
}
|
|