Which is cheaper and preferable: put1 or put2?
Map<String, Animal> map = new Map<String, Animal>();
void put1(){
for (.....)
if (Animal.class.isAssignableFrom(item[i].getClass())
map.put(key[i], item[i]);
void put2(){
for (.....)
try{
map.put(key[i], item[i]);}
catch (...){}
Question Version : The question was not so clear. Let me review the question a little. I forgot the casting, so put2 depends on the failure of the exception exception exception. isAssignableFrom (), isInstanceOf () and instanceof are functionally similar and, therefore, bear the same costs, one of them is a method of including subclasses, and the second for exact type matching, and the third is the version of the operator. Both reflexive methods and exceptions are expensive operations.
My question for those who have done some benchmarking in this area is which is cheaper and preferable: instanceof / isassignablefrom vs cast exception?
void put1(){
for (.....)
if (Animal.class.isAssignableFrom(item[i].getClass())
map.put(key[i], (Animal)item[i]);
void put2(){
for (.....)
try{
map.put(key[i], (Animal)item[i]);}
catch (...){}