A block of code similar to this sparked some debate on to which part of the code was most efficient or if there was a more correct way to do this. One argument was that the cast was more efficient than creating a string to parse. One argument was that the multiple class casts was creating more objects than creating the string to parse.
What is the “best practice”?
Object some_num_obj;
double some_num;
if(some_num_obj instanceof Integer)
{
some_num = (double) (int) (Integer) some_num_obj;
}
else if(some_num_obj instanceof Double)
{
some_num = (Double) some_num_obj;
}
else
{
some_num = Double.parseDouble(some_num_obj.toString());
}
The most efficient and possibly the fastest is to use Number.doubleValue and Double.parseDouble