Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Determine value type

 
Adrian Yan
Ranch Hand
Posts: 688
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Adrian Yan
Ranch Hand
Posts: 688
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic