I have a heterogeneous List that can contain any arbitrary type of object. I have a need to find an element of the List that is of a certain type. Looking through the answers of other generics related questions, I’m not finding exactly what I need.
Here’s an example of what I’m trying to accomplish:
List <Object> list = new ArrayList <Object>();
...
private someMethod() {
Customer cust = findInList( Customer.class );
Invoice inv = findInList( Invoice.class );
}
So, how do I define findInList using generics? I gather that type erasure causes issues here and I don’t know as much about that as I probably should, but I’d rather not define multiple “find” methods since there could be dozens of different types of objects living in the List.
You can define the method using [
Class.isInstance()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#isInstance(java.lang.Object)) and [Class.cast()](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#cast(java.lang.Object)) method. Here is a sample implementation (with extra argument for the list):Update: I would recommend against putting multiple types in the
Collection. It’s usually a sign that either need a custom datatype (e.g.Transaction) or a Tuple value.