Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Adding two generic number types

843793Feb 28 2006 — edited May 28 2006
Hi all,

As a small exercise I am trying to devise a generic maths class that can add two numbers together either Integer, Float and Double types.


I have written the following code
class Test {

public static void main(String args[]) {

	MathClass<Integer> integers = new MathClass<Integer>();

	Integer i= new Integer(2);
	System.out.println(integers.add(i,i));
	}
}


class MathClass<T> {

	public T add(T a, T b) {

		return a + b;
	}

	public T subtract(T a, T b) {
		return a - b;
	}

	public T multiply(T a, T b) {
		return a * b;
	}

	public T divide(T a, T b) {
		return a / b;
	}

}
But I get a compile error which says that I can't use the + - * / operators on T.

Yet something like the following code works
public class Test2 {
   public static void main(String[] args) {
     Integer i = new Integer(2);
     Integer o = new Integer(2);
     System.out.println(i + o);
   }
}
Is there a way to make the generic maths class work as I would like?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 25 2006
Added on Feb 28 2006
9 comments
3,660 views