[英]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.我有一个通用的 class 来表示一行值中的一个区间。
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'
但是调用Arrays.sort
的行,有一个编译器警告: Unchecked call to 'compareTo(T)' as a member of raw type 'java.lang.Comparable'
The unchecked warning comes about because of your raw-typed array, new Interval[0]
.未经检查的警告是由于您的原始类型数组new Interval[0]
引起的。
Note that you're not sorting intervals
, you're sorting a copy of it, and then discarding the sorted copy.请注意,您不是对intervals
进行排序,而是对它的副本进行排序,然后丢弃排序后的副本。
Why bother going to an array?为什么要麻烦去一个数组?
intervals.sort(/* your comparator */);
Also, your comparator is unnecessarily complicated:此外,您的比较器是不必要的复杂:
Comparator.comparing(Interval::getStart)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.