Figuring out whether a number is a Double in Java
Since this is the first question from Google I'll add the JavaScript style typeof
alternative here as well:
myObject.getClass().getName() // String
Try this:
if (items.elementAt(1) instanceof Double) {
sum.add( i, items.elementAt(1));
}
Reflection is slower, but works for a situation when you want to know whether that is of type Dog or a Cat and not an instance of Animal. So you'd do something like:
if(null != items.elementAt(1) && items.elementAt(1).getClass().toString().equals("Cat"))
{
//do whatever with cat.. not any other instance of animal.. eg. hideClaws();
}
Not saying the answer above does not work, except the null checking part is necessary.
Another way to answer that is use generics and you are guaranteed to have Double as any element of items.
List<Double> items = new ArrayList<Double>();