[英]Collections.sort(), gives “unchecked or unsafe operation” Error?
我从Java版本8中收到错误:“使用未经检查或不安全的操作”。
看来问题出在Collections.sort()
,但是问题是什么呢? 我检查了Java Doc,一切似乎都很好,除了参数是List
,而就我而言, ArrayList
是List
呢?
import java.util.ArrayList;
import java.util.Collections;
public class Driver
{
public static void test()
{
ArrayList<Person> persons = new ArrayList<Person>();
persons.add(new Person("Hans", "Car License"));
persons.add(new Person("Adam", "Motorcycle License"));
persons.add(new Person("Tom", "Car License"));
persons.add(new Person("Kasper", "Car License"));
System.out.println(persons);
Collections.sort(persons);
System.out.println(persons);
System.out.println(Collections.max(persons));
System.out.println(Collections.min(persons));
}
}
我怀疑您的班级Person
是以这种方式声明的:
class Person implements Comparable {
...
@Override
public int compareTo(Object o) {
...
}
}
更改为
class Person implements Comparable<Person> {
...
@Override
public int compareTo(Person o) {
...
}
}
不要使用原始类型 。
当编译器无法使用Generics检查类型是否安全地使用了集合时,将出现此错误。 因此,您需要指定要存储在集合中的对象的类型。
正如Tagir所指出的那样,在声明类Person
时,您可能未提供类型,因此编译器会给您错误。 如果需要更详细的信息,可以使用"-Xlint:unchecked"
开关重新编译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.