1

I was trying to learn Generics in Java.

I created a box class.

package com.generic;

public class Box<T> {

    T length;   
    T breadth;
        // Setter and getter

}

Now I wanted to create a method to caluclate area of the box which will be length * breadth.

I have made it generic so I can use Long , Double, Integer etc.

But when i tried to create a method calculateArea like this

T area(T w , T h)
    {
        return (w * h); 
    }

But it is giving me compile time error.

I think multiplication can't be performed on generics.

So what i can do to make my area method generic?

Thanks.

smith
  • 37
  • 2

4 Answers4

4

I dont think theres any good solution for that. Anyway, try this

class Box<T extends Number> {
    T length;
    T breadth;

    T area(T w , T h) {
        if (w instanceof Double) {
            return (T) w.getClass().cast(w.doubleValue() * h.doubleValue()); 
        }
        if (w instanceof Long) {
            return (T) w.getClass().cast(w.longValue() * h.longValue()); 
        }
        if (w instanceof Integer) {
            return (T) w.getClass().cast(w.intValue() * h.intValue()); 
        }
        throw new IllegalArgumentException();
    }
}
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • Yes, there is no solution other than the above. The reason is that arithmetic operators work on primitive types and not on classes (generic or not). Number can't be boxed since the primitive type is ambiguous. – Jilles van Gurp Jun 30 '13 at 10:04
1

This may work

public class Box<T extends Number> {

T length;
T breadth;
// Setter and getter


public T getLength() {
    return length;
}

public void setLength(T length) {
    this.length = length;
}

public T getBreadth() {
    return breadth;
}

public void setBreadth(T breadth) {
    this.breadth = breadth;
}

Number area(T w , T h)
{
   return (w.doubleValue()*h.doubleValue());
}
}
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
0

Since T is an object and you want to perform '*' on it, you need your inner objects to be primitives, but only numbers.

'T' could also be a string or a boolean, so java must protect you from using '*' on any given 'T'.

You need Generics to Box and UnBox your primitives automatically as 'int', 'float' or 'double', do the calculation, and Box them.

I don't know if it can be done in the way you wrote your Area method.

EDIT:

OR, you can use the Evgeniy's posted answer, and do the Boxing/UnBoxing manually...

Shahar
  • 655
  • 2
  • 7
  • 23
0

Compiler does not know the T on compile, whether T is a value type or a reference type. It will give compile time error because we can perform primitive operation on value types only not on reference types so you have to tell the compiler the type of T in advance

class Box<T extends whatYouWant> {
    T length;
    T breadth;
//more stuff
}
Haseeb Asif
  • 1,766
  • 2
  • 23
  • 41