泛型应用遇到的一个小问题.
关于泛型也看了一些相关的文章,昨天写了一个程序,编译提示
(注意: TestComparable.java 使用了未经检查或不安全的操作。
注意: 要了解详细信息,请使用 -Xlint:unchecked 重新编译。)
我反复查找没发现.希望能有能人指点一下!以下是我写的代码:
import java.util.*;
public class TestComparable
{
public static void main(String[] args)
{
List <Student> l=new ArrayList <Student> ();//泛型类的语法。
//List l=new ArrayList();
l.add(new Student( "hlonger ",30));
l.add(new Student( "bluelaster ",33));
l.add(new Student( "keep ",32));
l.add(new Student( "mk ",31));
Collections.sort(l); //好象主要这有问题
print(l);
}
public static void print(List <Student> c)
{
/*
for(Student s:c)
System.out.println(s);
*/
Iterator it=c.iterator();
while(it.hasNext())
{
//Object o=it.next();
//Student s=(Student)o;
System.out.println(it.next());
}
}
}
class Student implements Comparable
{
private String name;
private int age;
public Student(){}
public Student(String name,int age)
{
this.name=name;
this.age=age;
}
public String toString()
{
return "Student: "+name+ " Age: "+age;
}
public int compareTo(Object o)
{
Student s=(Student)o;
return this.age-s.age;//不是s.this-o.age
}
}
------解决方案--------------------class Student implements Comparable <Student> {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "Student: " + name + " Age: " + age;
}
public int compareTo(Student o) {
Student s = (Student) o;
return this.age - s.age;// 不是s.this-o.age