- import java.util.*;
- public class GenericDemoT {
- public static void main(String[] args)
- {
- //ArrayList<String> a1 = new ArrayList<String>(new MyLenCom()); //代码1
- TreeSet<String> a1 = new TreeSet<String>(new MyLenCom()); //代码2
- //<String>代表要村的元素的类型
- a1.add("abcd2");
- a1.add("aadc");
- a1.add("cdfgd2");
- a1.add("123");
- a1.add(",..,m,");
-
- Iterator<String> it = a1.iterator();
- while(it.hasNext())
- {
- String s = it.next();
- System.out.println(s+"....."+s.length());
- }
-
- }
- }
- class MyLenCom 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;
- }
- }
复制代码 疑问:为什么代码2能编译通过,而代码1就不能?ArrayList和TreeSet在这一点有什么区别?
|
|