Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics - Legal alternative for (elements instanceof List<? extends Comparable>)

I have this method which unique parameter (List elements) sets elements to a ListModel, but I need to make a validation to see if the generic type implements comparable and since such thing like:

if (elements instanceof List<? extends Comparable>)

is illegal, I don't know how to do the proper validation.

Update

I already have done this validation using:

(elements.size() > 0 && elements.get(0) instanceof Comparable)

but I want to know if is there a cleaner solution for that, using for example reflection?

Thanks in advance.

like image 584
Juan Diego Avatar asked Aug 07 '11 19:08

Juan Diego


People also ask

What is generic comparable?

Comparability expresses the innate ability to be sorted in a list, and so many Java types are comparable, like Integer, String, etc. The way a class implements this interface is that T must be the class itself, for example, if you look at the String class: public class String implements Comparable<String> ...

What are not allowed for generics?

Cannot Use Casts or instanceof With Parameterized Types. Cannot Create Arrays of Parameterized Types. Cannot Create, Catch, or Throw Objects of Parameterized Types. Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same Raw Type.

What are generic methods?

Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.

How do you create a variable for a generic type in Java?

It specifies the type parameters (also called type variables) T1, T2, ..., and Tn. To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class.


2 Answers

The generic type of a list is erased at runtime. For this to work you need to either require the parameter in the method signature or test each element individually.

public void doSomething(List<? extends Comparable> elements) {}

OR

for (Object o : elements) {
    if (o instanceof Comparable) {}
}

If you have control over the code, the former is preferred and cleaner; the later can be wrapped in a utility method call if needed.

like image 172
Andrew White Avatar answered Sep 23 '22 02:09

Andrew White


That's not possible. instanceof is a runtime operator whereas generic information is lost at runtime (type-erasure).

like image 44
hoipolloi Avatar answered Sep 22 '22 02:09

hoipolloi