1

I get the error from Java Version 8: "uses unchecked or unsafe operations".

It seems like the problem is comming from Collections.sort(), but what is the problem? I've checked the Java Doc and everything seems to be fine, except that the argument is a List, but ArrayList is a List as far as I'm concerned?

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));
    }
}
Praneeth
  • 1,260
  • 18
  • 37
Shuzheng
  • 11,288
  • 20
  • 88
  • 186

2 Answers2

11

I suspect your class Person is declared this way:

class Person implements Comparable {
    ...

    @Override
    public int compareTo(Object o) {
        ...
    }
}

Change it to

class Person implements Comparable<Person> {
    ...

    @Override
    public int compareTo(Person o) {
        ...
    }
}

Do not use rawtypes.

Community
  • 1
  • 1
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
0

This error comes when the compiler is not able to check that the collection is used in a type-safe way, using Generics. So you need to specify the type of objects you are storing in your collection.

As Tagir has pointed out that you are probably not providing the type when you are declaring your class Person, so the compiler is giving you the error. If you want a more detailed information you can recompile with the "-Xlint:unchecked" switch.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331