泛型的一点小疑惑:- import java.util.*;
- public class GenListTest {
-
- public static void PrintElements(Collection<String> c)
- {
- Iterator<String> it =c.iterator();
- while(it.hasNext())
- {
- System.out.println(it.next());
- }
- }
- public static void main(String[] args)
- {
- List<String> l=new ArrayList<String>();
- l.add(new Person(20,"zhangsan"));<font color="#ff0000">//这样的写法错误,正确的应该怎么写?</font>
- l.add(new Person(23,"lisi"));
- System.out.println(l.size());
- Collections.sort(l);
- PrintElements(l);
- }
- }
- class Person implements Comparable<Person>
- {
- private int age;
- private String name;
- Person(int age,String name)
- {
- this.age=age;
- this.name=name;
- }
- public int compareTo(Person p)
- {
- return age>p.age ? 1 :(age==p.age ? 0 :-1);
- }
- }
复制代码 对于l的add方法使用泛型的话,如上添加不正确,new Person(20,"zhangsan")这个的话正确的add方法应该是怎么样的?求解答。
|