练习:按照字符串长度排序。- import java.util.*;
- class TreeSetTest
- {
- public static void main(String[] args)
- {
- TreeSet ts = new TreeSet(new StrLenComparator());
- 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 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()));
- int num = s1.length().compareTo(s2.length());
- if(num==0)
- return s1.compareTo(s2);
- return num;
- }
- }
复制代码
注释的是毕老师原来的代码,新建Integer对象比较,下面一行是我直接用字符串长度比较,这两条语句运行的结果是一样的,我想问毕老师用Inter比较的用意是什么,还有直接用字符串比较是不是有什么弊端 |