aspose file tools*
The moose likes Java in General and the fly likes Determine value type Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Determine value type" Watch "Determine value type" New topic
Author

Determine value type

Adrian Yan
Ranch Hand

Joined: Oct 02, 2000
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

Joined: Oct 10, 2003
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

Joined: Jan 30, 2000
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 ]

"I'm not back." - Bill Harding, Twister
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
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.


Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Adrian Yan
Ranch Hand

Joined: Oct 02, 2000
Posts: 688
Yea, that's what I had before, Mike. The problem is that Number does not support arithmetic, so I have to convert it anyway. I'll just have to bite the bullet and do it the hard way. Damn STRONGLY TYPE LANGUAGE!!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Determine value type