Java generics: how to distinguish (T extends Comparable <? Super T>) without raw types
I wonder if it is possible to distinguish the incompatible with something so that it matches the parameter of the method T, which has the template type <T extends Comparable<? super T>> <T extends Comparable<? super T>> as the Collections.sort() method
public static <T extends Comparable<? super T>> void sort(List<T> list) Suppose I have a link to a list of disparate ones and you want to call this method by doing the following:
List<E> foo = new List<E>(a); Collections.sort( /* magic cast */ foo); I can do this if I go to (List<? extends Comparable>) , but this raises a warning that I'm using raw types (in this case, it compares without template types). Let's say I want to avoid using raw types or even suppress them via @SuppressWarnings("rawtypes") (for example, to preserve backward compatibility and avoid raw types).
Is it possible to avoid using raw types by dropping on (List<? extends Comparable</*something*/>>) and what would it be if something were "(an unchecked listing is permissible)?
EDIT . This example is just to illustrate this point. Actually, I don’t have a comparable one and I don’t want to sort anything, but I just need to dynamically check that something is of some type (comparable in this example) (via instanceof), and then pass some argument to the method, which has template arguments similar to the Collections.sort() method.
Pass it
Collections.sort((List<Comparable<Object>>) list); This will not give rawtype warnings. Only one “untested throw” warning (which you will receive anyway.)
Judging by what you mentioned in EDIT , do you end up wanting to do something like this?
if(!list.isEmpty() && list.get(0) instanceof Comparable){ List<Comparable<Object>> cmprList = (List<Comparable<Object>>)list; Collections.sort(cmprList); } This, of course, is impossible. Collections.sort requires Comparable to call the compareTo() method. So, in your presentation, what should happen when the sorting gets a collection of disparate objects?
Perhaps you want to use something like ordered by default, based on links, for example. But such a thing does not exist implicitly. Although, this can be implemented. But I doubt that this is what you want? So why do you want to sort the list first? And how should these items be sorted?
This will be compiled in Eclipse:
List<?> foo = new ArrayList<Object>(); Collections.sort((List<Comparable>) foo); You will receive a "Security Type: Unverified" warning, which you can suppress with this:
@SuppressWarnings("unchecked") This will allow you to call sorting. Is this what you are looking for? There is no guarantee that it will be safe at runtime, of course.