java中用到ArrayList.sort()为什么会出现“使用了未经检查或不安全的操作”的提示?求高手解答 10
importjava.util.*;classArrayListTest{publicstaticvoidprintElements(Collectionc){Itera...
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)
{
Student s1=new Student(2,"zhangsan");
Student s2=new Student(1,"lisi");
Student s3=new Student(3,"wangwu");
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);
al.add(s2);
al.add(s3);
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;
return num>s.num?1:(num==s.num?0:-1);
}
public String toString()
{
return num+":"+name;
}
} 展开
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)
{
Student s1=new Student(2,"zhangsan");
Student s2=new Student(1,"lisi");
Student s3=new Student(3,"wangwu");
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);
al.add(s2);
al.add(s3);
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;
return num>s.num?1:(num==s.num?0:-1);
}
public String toString()
{
return num+":"+name;
}
} 展开
3个回答
展开全部
存在类型匹配隐患,在个人用一般没问题,自己能确认类型无误,在main()上面加@SuppressWarnings("unchecked")就行
要是给别人用或者教常用和可能以后需要扩展,还是改了好。
1,.Student类的定义改为class Student implements Comparable<Student>
2.类中的方法改为
public int compareTo(Student s) {
return num > s.num ? 1 : (num == s.num ? 0 : -1);
}
要是给别人用或者教常用和可能以后需要扩展,还是改了好。
1,.Student类的定义改为class Student implements Comparable<Student>
2.类中的方法改为
public int compareTo(Student s) {
return num > s.num ? 1 : (num == s.num ? 0 : -1);
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询