Java Collections.sort(),给出;未经检查或不安全操作”;错误?
我从Java版本8中得到错误:“使用未检查或不安全的操作” 问题似乎来自Java Collections.sort(),给出;未经检查或不安全操作”;错误?,java,collections,Java,Collections,我从Java版本8中得到错误:“使用未检查或不安全的操作” 问题似乎来自Collections.sort(),但问题是什么?我检查了Java文档,一切似乎都很好,除了参数是一个列表,但是ArrayList在我看来是一个列表 import java.util.ArrayList; import java.util.Collections; public class Driver { public static void test() { ArrayList<
Collections.sort()
,但问题是什么?我检查了Java文档,一切似乎都很好,除了参数是一个列表
,但是ArrayList
在我看来是一个列表
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));
}
}
import java.util.ArrayList;
导入java.util.Collections;
公务舱司机
{
公共静态无效测试()
{
ArrayList persons=新建ArrayList();
人员。添加(新人员(“Hans”、“汽车牌照”);
新增(新人员(“Adam”、“摩托车执照”);
人员。添加(新人员(“汤姆”、“汽车牌照”);
添加(新人员(“Kasper”、“汽车牌照”);
系统输出打印(人);
收集.分类(人);
系统输出打印(人);
System.out.println(Collections.max(persons));
System.out.println(Collections.min(persons));
}
}
我怀疑你的类人
是这样声明的:
class Person implements Comparable {
...
@Override
public int compareTo(Object o) {
...
}
}
换成
class Person implements Comparable<Person> {
...
@Override
public int compareTo(Person o) {
...
}
}
class-Person实现可比性{
...
@凌驾
公共内部比较(o人){
...
}
}
不要使用。我怀疑您的类
人
是这样声明的:
class Person implements Comparable {
...
@Override
public int compareTo(Object o) {
...
}
}
换成
class Person implements Comparable<Person> {
...
@Override
public int compareTo(Person o) {
...
}
}
class-Person实现可比性{
...
@凌驾
公共内部比较(o人){
...
}
}
请勿使用。当编译器无法使用检查集合是否以类型安全的方式使用时,会出现此错误。因此,您需要指定要存储在集合中的对象的类型
正如Tagir指出的,在声明类
Person
时,可能没有提供类型,因此编译器会给出错误。如果需要更详细的信息,可以使用“-Xlint:unchecked”
开关重新编译。当编译器无法使用检查集合是否以类型安全的方式使用时,会出现此错误。因此,您需要指定要存储在集合中的对象的类型
正如Tagir指出的,在声明类
Person
时,可能没有提供类型,因此编译器会给出错误。如果您想要更详细的信息,您可以使用“-Xlint:unchecked”
开关重新编译。可能的重复,但您忘记了最重要的部分:向我们显示类Person
@jaehonee的代码,不同意。问题是关于编译器警告,而不是如何排序。看一看可能发生的重复,你忘记了最重要的部分:向我们展示类Person
@JaeHeonLee的代码,不同意。问题是关于编译器警告,而不是关于如何排序。让我们看一看如何得到一个好的答案。请简短地解释一下/link为什么应该避免使用rawtypes?@RobAu,在规范的“不要使用rawtypes”问题中添加了链接。回答得好。还请简要解释/link为什么应该避免使用rawtypes?@RobAu,添加了规范的“请勿使用rawtypes”问题的链接。