Question

I would like to know how to ask if a java object is a List or an ArrayList.

For example:

if (Object instanceof List <?>)) {
    // Do something
}

PS: I have several lists of different types and would like to implement the method for any list no matter what type of data they contain.

Était-ce utile?

La solution

To test if an instance is a List or an ArrayList1, just use instanceof.

Note that according to the JLS 15.20.2, the type operand of the instanceof operator must be a reifiable type, and that is defined in JLS 4.7 as:

  • a parameterized type in which all type arguments are unbounded wildcards,
  • a raw type
  • a primitive type (not applicable in this context
  • an array type whose element type is reifiable, or
  • a nested type where, each enclosing type is also reifiable.

So both of these should be valid:

if (obj instanceof List)) {     // raw type
    // Do something
}
if (obj instanceof List <?>)) { // type parameter is an unbounded wildcard
    // Do something
}

but this would be a compilation error:

if (obj instanceof List <Integer>)) {
    // Do something
}

I have several lists of different types and would like to implement the method for any list no matter what type of data they contain.

That's no problem.

(But it would be a problem if you wanted the method to only work for lists with certain kinds of data ... based on a simple runtime typecheck. The type parameters for a generic type are not available at runtime for runtime tests, so you would need to test each element of the list individually ...)


1 - Note that any ArrayList is also a List ... because the ArrayList class implements the List interface.

Autres conseils

"List" is only an interface. The implementation is eq. "ArrayList" or "LinkedList".

But here is another topic from Stackoverflow:

how-to-instanceof-listmytype

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top