Java's equivalent to C#'s default(T)
is null
, which clearly would not work in your case, because you would get a NullPointerException the first time you tried to add something to your total.
In order to initialize your total you would need a factory method in java, but it still would not work, because:
- you cannot use
+=
on generics in java.
java.lang.Number
is immutable, so you cannot add anything to it.
You have two options.
The massively overengineered approach:
Define a new interface called, say, MyNumber
which contains an add
method, and write associated non-immutable numeric classes implementing this interface, so your code would then look like this:
@Override
public <T extends MyNumber> T add( T total, Iterable<T> myNumbers )
{
for( T myNumber : myNumbers )
total.add( myNumber );
return total;
}
(You would also need to write a factory so that you can create an instance to hold your total without knowing precisely what type it is.)
The pragmatic approach:
Write cascaded if
statements like this:
if( number instanceof Integer )
{
//declare int total
//loop to sum integers
//box the total into a Number
}
else if( number instanceof Long )
{
//declare long total
//loop to sum longs
//box the total into a Number
}
...