This week's book giveaway is in the Design forum.We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!

# Determine value type

Ranch Hand
Posts: 688
I'm doing a math class that can add array of numbers. My question is, what's the best to detemine what type of value the array has? For example: user can pass an array of Integer, and an array of Double, before I can do any math work on them, I need to find out what type I should convert them to. Anyone know a good way to do this besides getClass() method?

don cline
Ranch Hand
Posts: 35
Sure, assuming that you have an object array, you can do the following:
public doMath(Object [] values)
{
for (int i=0;i<values.length;i++)
{
if (values[i] instanceof Integer)
{
//treat this as an Integer
}
else if (values[i] instanceof Double)
{
//treate this as a Double
hopes this helps...
Don Cline

Jim Yingst
Wanderer
Sheriff
Posts: 18671
Alternately you can write the method profile to specify the type you're dealing with - and subsequently you know exactly what you're dealing with, as the compiler and JVM won't allow any other type to be passed. E.g.

If you need to convert one array of primitives to an array of another type of primitive, you need to write a method to do this, e.g.:

[ December 13, 2003: Message edited by: Jim Yingst ]

Michael Morris
Ranch Hand
Posts: 3451
If your array is of one of the wrapper classes (Integer, Double, etc) you could keep the method generic:

All of the numeric wrapper classes extend the Number class which has methods to convert to any of the primitives (intValue, doubleValue, etc.) Depending on how you are going to process the array, you could use one of those methods to convert the values before performing the math. You could also convert the values to BigIntegers or BigDecimals if concerned about loss of precision.