import java.util.*;
class ArrayListTest
{
public static void printElements(Collection c)
{
Iterator it = c.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}

public static void main(String[] args)
{
ArrayList<Student> al = new ArrayList<Student>();
                  al.add(new Student(2, "xiao2"));
al.add(new Student(3, "zhangsan"));
al.add(new Student(2, "axiao2"));
al.add(new Student(4, "xiao2"));
printElements(al);
System.out.println("-------------------------------------");
Collections.sort(al);
printElements(al);
}
}class Student implements Comparable
{
int num;
String name;
Student(int num, String name)
{
this.num = num;
this.name = name;
}
public int compareTo(Object o)
{
Student s = (Student)o;
if(this.num > s.num)
return 1;
else if(this.num < s.num)
return -1;
else
{
return this.name.compareTo(s.name);
}
}
public String toString()
{
return num+":"+name;
}
}为什么编译的时候总是报:
注意:ArrayListTest.java 使用了未经检查或不安全的操作。
注意:要了解详细信息,请使用 -Xlint:unchecked 重新编译。
把Collections.sort(al);这行注释了就不会这个警告

解决方案 »

  1.   

    Sutdent类实现的接口稍微动一下,就OK了class Student implements Comparable<Student> {
    int num;
    String name; Student(int num, String name) {
    this.num = num;
    this.name = name;
    } public int compareTo(Student o) {
    Student s =  o;
    if (this.num > s.num)
    return 1;
    else if (this.num < s.num)
    return -1;
    else {
    return this.name.compareTo(s.name);
    }
    } public String toString() {
    return num + ":" + name;
    }
    }
    如果你有eclipse时的,系统会给你提示的
      

  2.   

    从jdk1.5开始增加了泛型编程功能,增加了类型安全检查,避免不安全类型出现,不过楼上代码不会出错,只会警告,我把你的代码修改如下:import java.util.*;class ArrayListTest {
    public static void printElements(Collection<Student> c) {
    Iterator<Student> it = c.iterator();
    while (it.hasNext()) {
    System.out.println(it.next());
    }
    }
    public static void main(String[] args) {
    ArrayList<Student> al = new ArrayList<Student>();
    al.add(new Student(2, "xiao2"));
    al.add(new Student(3, "zhangsan"));
    al.add(new Student(2, "axiao2"));
    al.add(new Student(4, "xiao2"));
    printElements(al);
    System.out.println("-------------------------------------");
    Collections.sort(al);
    printElements(al);
    }
    }class Student implements Comparable<Student> {
    int num;
    String name;
    Student(int num, String name) {
    this.num = num;
    this.name = name;
    }
    @Override
    public int compareTo(Student o) {
    if (this.num > o.num)
    return 1;
    else if (this.num < o.num)
    return -1;
    else {
    return this.name.compareTo(o.name);
    }
    }
    public String toString() {
    return num + ":" + name;
    }}