I found
this related thread, with no answer to my question.
In the below code, there is a certain level of redundancy in that I am checking that I can do the Class.cast() prior to doing it, via Class.isInstance().
I can either omit the isInstance() check and just count on cast() throwing an exception, or I can ignore the ClassCastException (do nothing in the catch block, as shown below).
Which is better? Is it faster if I just omit the instance check and let cast() detect the errors? Is there a style convention here?
protected <T extends ParentClass> List<T> getItemsOfType(Class<T> clazz){
List<T> retval = new ArrayList<T>();
for(ParentClass t : items.values()){
if(clazz.isInstance(t)){
try{
retval.add(clazz.cast(t));
}
catch(ClassCastException cce){
// should never happen
}
}
}
}
Thanks for your time