subject-q
subject-q

Reputation: 135

How to get rid of Unchecked call to 'compareTo(T)' warning?

I have a generic class to represent an interval in a line of values.

public class Interval<T extends Comparable<T>> {

    private boolean isStartInclusive;
    private T start;
    private T end;
    private boolean isEndInclusive;

    //constructors and getters and setters

}

I have a list of this interval of same type. And I am trying to sort them, based on their starting value.

So if the list was

{[1,2], [0,3], [-10,4]}

I am trying to get

{[-10,4], [0,3], [1,2]}

or

If the list was

{['e','v'], ['a','d'], ['c','f']}

I am trying to get

{['a','d'], ['c','f'], ['e','v']}

The code for sorting is below.

public static <T extends Comparable<T>> List<Interval<T>> sortIntervals(List<Interval<T>> intervals) {

    Interval[] intervalsArray = intervals.toArray(new Interval[0]);
    Arrays.sort(intervalsArray, (o1, o2) -> o1.getStart().compareTo(o2.getStart()));

    return Arrays.asList(intervalsArray);

}

But the line where Arrays.sort is called, there is a compiler warning: Unchecked call to 'compareTo(T)' as a member of raw type 'java.lang.Comparable'

Upvotes: 0

Views: 79

Answers (1)

Andy Turner
Andy Turner

Reputation: 140514

The unchecked warning comes about because of your raw-typed array, new Interval[0].

Note that you're not sorting intervals, you're sorting a copy of it, and then discarding the sorted copy.

Why bother going to an array?

intervals.sort(/* your comparator */);

Also, your comparator is unnecessarily complicated:

Comparator.comparing(Interval::getStart)

Upvotes: 3

Related Questions