0

I am attempting to write a function that calculates the absolute maximum with an Object input. I am using an old version of the JRE (1.4), so generics are not an option. I wrote a function for returning the maximum using Comparable, but I would like to return the absolute maximum (smallest negative or largest positive). Here is my code for returning the maximum:

public Object getResult(Object objA, Object objB) {
    if (objA == null) return objB;
    return ((Comparable)objA).compareTo(objB) > 0 ? objA : objB;
}

The arguments will always be primitive types converted to their boxed counterparts, i.e: Float, Double, Integer, etc.

In order to find the absolute maximum, I need to get the absolute value. However, I cannot get the maximum value since these are abstract Object objects, and I cannot retrieve their values. What is the best way of doing this?

Hans Landa
  • 105
  • 2
  • 9

3 Answers3

0

A bit hacky, but works, and without instanceof for each of the primitives types:

public static Object getResult(Number n, Number m) {
    if (n == null) return m;

    double nd = n.doubleValue();
    double md = m.doubleValue();

    // Now you have two double numbers and you can find their
    // absolute maximum easily
    ...
}
SHG
  • 2,516
  • 1
  • 14
  • 20
  • Why not just use [`doubleValue()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Number.html#doubleValue--)? – Mureinik Jun 09 '17 at 17:02
  • Yeah, but it has poor performance and the return type always is double. – m.ghoreshi Jun 09 '17 at 17:12
  • 1) Wrong, the return value is `Object` or `Number` so the caller must use casting anyway. 2) What makes its performance poor?? Especially when I don't have to ask `if (instanceof X)` for each of the primitive types? – SHG Jun 09 '17 at 17:18
0

You can use java.lang.Number instead of Object and convert the numbers to BigDecimal as suggested in https://stackoverflow.com/a/30479040/6307292:

new BigDecimal(number.toString())

This allows you to call the abs - method and then compare the numbers.

The solution looks ugly, but it addresses possible precision-problems when comparing different types.

mm759
  • 1,404
  • 1
  • 9
  • 7
-1

You should use instanceof and casting to check for each type you intersted in (I suppose you are going to calculate the absolute maximum value; if you want to return the object which is absolute maximum you can use the compare method and compare to the Zero as another answer mentioned):

public Object getResult(Object objA, Object objB) {
    if(objA instanceof Integer && objB instanceof Integer){
        Integer aInt=(Integer)objA;
        Integer bInt=(Integer)objB;
        //calculate and return...
    }
    //elseif objA instanceOf Long and so on for other types
m.ghoreshi
  • 782
  • 5
  • 12
  • The cast can be avoided by overloading the method. I mean writing one method for each type. – mm759 Jun 09 '17 at 16:54