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);这行注释了就不会这个警告
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时的,系统会给你提示的
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;
}}