这是 按照字符串长度排序的练习,覆写的compare函数的返回值类型是int,为什么不能用两个长度值直接相减作为返回值呢?
public class TreeSetTest {
public static void main(String[] args) {
// TODO 自动生成的方法存根
TreeSet ts = new TreeSet(new StringLengthCompare());
ts.add("abcd");
ts.add("cc");
ts.add("cba");
ts.add("aaa");
ts.add("z");
ts.add("hahaha");
Iterator it = ts.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
class StringLengthCompare implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1 = (String)o1;
String s2 = (String)o2;
int num = s1.length()-s1.length();
if(num == 0)
{
return s1.compareTo(s2);
}
return num;
}
}
|
|