We are migrating our existing code from Java 1.5 to Java 8, and while compiling with -Xlint, I came across warnings like "unchecked call to compare(T,T)
as a member of the raw type Comparator
".
I roughly understand that I need to somehow tell which datatype I'd be passing in to Comparator
, but I'm using generics so I can pass in different datatypes, so how can I eliminate this warning.
Here's a snippet of my code where I'm seeing this warning:
private static void mergeSort(Object[] source, int[] src,int[] dest,
int low, int high, int off, Comparator c) {
int length = high - low;
for (int i=low; i<high; i++)
for (int j=i; j>low && c.compare(source[dest[j-1]], source[dest[j]])>0; j--) {
int t = dest[j];
dest[j] = dest[j-1];
dest[j-1] = t;
}
return;
}
And, this is being called as:
public void setSort( Comparator<T> comparator) {
List<T> currentList = getCurrentList();
int[] dst = new int[currentList.size()];
for (int i=0; i< currentList.size(); i++)
dst[i]=i;
int [] src = dst.clone();
mergeSort (currentList.toArray(), src, dst,0, dst.length, 0, comparator );
}
Since I'm already saying Comparator<T> comparator
in setSort()
method, why am I still getting the below error?
warning: [unchecked] unchecked call to compare(T,T) as a member of the raw type Comparator [multiant] for (int j=i; j>low && c.compare(source[dest[j-1]], source[dest[j]])>0; j--) {
As far as I can tell, you have to change the definition of mergeSort
:
public static <T> void mergeSort(Object[] source, int[] src, int[] dest,
int low, int high, int off, Comparator<T> c) {
And than you have to do a cast:
@SuppressWarnings("unchecked")
T[] sourceC = (T[]) source;
You know that the array is of type T
but you can't declare a generic array. But that's ok, since T
is going to be erased to Object
at runtime either way.
And the for loop slightly changes to use that:
for (int j = i; j > low && c.compare(sourceC[dest[j - 1]], sourceC[dest[j]]) > 0; j--)