Martin Nycander
Martin Nycander

Reputation: 1309

Typechecking and generics in java generates warnings

I have the following inline Comparator.

private static class SampleSorter implements Comparator<SampleClass>{
    public int compare(SampleClass o1, SampleClass o2) {
        if (o1 instanceof Comparable) {
            return ((Comparable) o1).compareTo(o2);
        } else if (o2 instanceof Comparable) {
            return -((Comparable) o2).compareTo(o1);
        }
        return 0;
    }
}

Which generates the following warnings:

Comparable is a raw type. References to generic type Comparable<T> should be parameterized


And if I instead parameterize the types as suggested:

        if (o1 instanceof Comparable) {
            return ((Comparable<SampleClass>) o1).compareTo(o2);

Then I get warnings...

Type safety: Unchecked cast from SampleClass to Comparable<SampleClass>


And if I do typechecking:

    if (o1 instanceof Comparable<SampleClass>) {
        return ((Comparable<SampleClass>)o1).compareTo (o2);

I get the following error:

Cannot perform instanceof check against type Comparable<SampleClass>. Use the form Comparable<?> instead since generic type information will be erased at runtime


And again, if I follow the advice of the error message:

    if (o1 instanceof Comparable<?>) {
        return ((Comparable<?>)o1).compareTo (o2);

I get this error:

The method compareTo(capture#4-of ?) in the type Comparable<capture#4-of ?> is not applicable for the arguments (SampleClass)


Now I don't know how to procede, I really prefere code which is warning- and error-free. How do I produce warning-free code with the wanted behaviour?

Upvotes: 2

Views: 150

Answers (2)

Matthias Bruns
Matthias Bruns

Reputation: 900

Try

 if (o1 instanceof Comparable<?>) {
        return ((Comparable<SampleClass>)o1).compareTo (o2);

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533492

The problem you have is there is no way for the compiler to know that what you are doing is safe. Instead you have to trust you know what you are doing and you can add this annotation

@SuppressWarnings("unchecked")

tot he method or the class and the warning go away.

Upvotes: 4

Related Questions