Collections.sort(),给出"未经检查或不安全的操作"错误?

Shu*_*eng 1 java collections

我从Java Version 8中得到错误:"使用未经检查或不安全的操作".

似乎问题来自于Collections.sort(),但问题是什么?我检查了Java Doc,一切似乎都很好,除了参数是a List,但ArrayListList我而言是一个?

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

Tag*_*eev 9

我怀疑你的课Person是这样宣布的:

class Person implements Comparable {
    ...

    @Override
    public int compareTo(Object o) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

将其更改为

class Person implements Comparable<Person> {
    ...

    @Override
    public int compareTo(Person o) {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

不要使用rawtypes.

  • 好答案.请简要解释/链接为什么应该避免使用rawtypes? (3认同)