Search code examples
javagenericscomparatorcomparableunsafe

Unchecked or unsafe operations without using annotation


I copied this piece of codes from a book I am currently reading...

import java.util.Comparator;

public class DefaultComparator<E> implements Comparator<E> {
    public int compare(E a, E b) throws ClassCastException {
        return ((Comparable<E>) a).compareTo(b);
    }
}

but it throws a compiler warning that it uses unchecked or unsafe operations. So how can I remove the warning without using the annotation @SuppressWarnings("unchecked")?


Solution

  • You need to make sure that E is extending the Comparable class:

    public class DefaultComparator<E extends Comparable<E>> implements Comparator<E> {
        public int compare(E a, E b) {
            return a.compareTo(b);
        }
    }