- /*
- 练习:按照字符串的长度排序
- */
- import java.util.*;
- class Demo3
- {
- public static void main(String[] args)
- {
- TreeSet tr=new TreeSet(new MyDemo());
- tr.add("abdc");
- tr.add("ab");
- tr.add("aa");
- tr.add("bcd");
- tr.add("asdfe");
- Iterator it=tr.iterator();
- while(it.hasNext())
- {
- System.out.println(it.next());
- }
- }
- }
- class MyDemo implements Comparator
- {
- public int compare(Object o1,Object o2)
- {
- String s1=(String)o1;
- String s2=(String)o2;
- /*
- if(s1.length()>s2.length())
- return 1;
- if(s1.length()==s2.length())
- return 0;
- return -1;
- */
- int num=new Integer(s1.length()).compareTo(new Integer(s2.length()));
- if(num==0)
- return s1.compareTo(s2);
- return num;
- }
- }
复制代码
|
|