So I have a generic ArrayList passed from parameter.
For example:
private <T> void testClass(ArrayList<T> data){
if(data[0] instanceof Foo){
//do something
} eles if(data[0] instanceof Bar){
//do something else
}
}
But the arraylist does not guarantee to have an element inside and could be empty, and get(0) will raise exception. How can I do this?
Edit:
How about non-initiated generic array?
For example:
private <T> void testClass(T[] data){
if(data.get(0) instanceof Foo){
//do something
} eles if(data.get(0) instanceof Bar){
//do something else
}
}
I tried T.class.getName().equals("Foo") but it does not work…
It’s not possible to tell the difference between an empty
ArrayList<String>and anArrayList<Integer>. That’s quite deliberate, due to type erasure. (That’s because there is no difference, at runtime.)Arrays are different. At least as long as the array was actually initialized with the literal type, you can use
array.getClass().getComponentType().