简体   繁体   中英

Unchecked cast from generic T to comparable preventing compile

I am supposed to be implementing mergesort without recursion. I've finished all that jazz, but the class is not compiling for reasons outside the domain of the homework assignment. Here is the problem:

This aspect is taken directly form the textbook...

 public <T extends Comparable<? super T>> void Mergesort(T[] a){
  T[] tmpArray =(T[]) new Comparable[a.length];

1 warning found:

File: /Users/OcastaEshu/Java/NonRecursiveMergesort.java [line: 22]

Warning: /Users/OcastaEshu/Java/NonRecursiveMergesort.java:22: warning: [unchecked] unchecked cast

found : java.lang.Comparable[] required: T[]

If you want to avoid the warning, you can do something like that:

public static <T extends Comparable<? super T>> void Mergesort(T[] a, Class<T[]> clazz) { 
    T[] tmpArray = clazz.cast(Array.newInstance(a.getClass().getComponentType(), a.length));
}

Where classOfelement is a.getClass() . I agree, it is ugly and you'd better use a @SuppressWarnings instead of that kind of code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM