Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I do arithmetic operations on the Number baseclass?

Tags:

java

I am trying to create a generic class in Java that will perform operations on numbers. In the following example, addition, as follows:

public class Example <T extends Number> {      public T add(T a, T b){         return a + b;     }  } 

Forgive my naivety as I am relatively new to Java Generics. This code fails to compile with the error:

The operator + is undefined for the argument type(s) T, T

I thought that with the addition of "extends Number" the code would compile. Is it possible to do this Java or will I have to create overridden methods for each Number type?

like image 370
Tom Smith Avatar asked Oct 06 '10 13:10

Tom Smith


People also ask

What are the 4 types of arithmetic operators?

Definition. The arithmetic operators perform addition, subtraction, multiplication, division, exponentiation, and modulus operations.

What is an example of an arithmetic operation?

Basic Arithmetic OperationsAddition (Finding the Sum; '+') Subtraction (Finding the difference; '-') Multiplication (Finding the product; '×' ) Division (Finding the quotient; '÷')

How do you calculate arithmetic operations?

Instead of using operators in mathematical expressions, you can perform basic arithmetic operations with the keywords ADD, SUBTRACT, MULTIPLY, and DIVIDE. p = n + m. ADD n TO m. P = m - n.

What is number of arithmetic operations?

The four arithmetic operations - addition, subtraction, multiplication, and division represents: Additions represent the sum of two values. Subtraction represents the difference between two numbers.


1 Answers

Number does not have a + operator associated with it, nor can it since there is no operator overloading.

It would be nice though.

Basically, you are asking java to autobox a descedant of Number which happens to include Integer, Float and Double, that could be autoboxed and have a plus operator applied, however, there could be any number of other unknown descendants of Number that cannot be autoboxed, and this cannot be known until runtime. (Damn erasure)

like image 51
Nathan Feger Avatar answered Oct 15 '22 23:10

Nathan Feger