本帖最后由 费破的可 于 2013-10-31 14:02 编辑
import java.util.*;
class TreeSetTest
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet(new StrLenComparator() );//为什么这里不加new StrLenComparator()程序也能运行???
ts.add("assa");
ts.add("afffa");
ts.add("ccaa");
ts.add("wwaa");
ts.add("wwaa");
ts.add("adfsf");
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;
}
}
|