Is it possible to write a single method `total`

to do a sum of all elements of an `ArrayList`

, where it is of type `<Integer>`

or `<Long>`

?

I cannot just write

`public long total(ArrayList<Integer> list) `

and

`public long total(ArrayList<Long> list) `

together as there will be an error of erasure, and `Integer`

does not automatically extends to `Long`

and vice versa... but the code inside is identical!

--------------Solutions-------------

Yes, you can implement such a method, since both `Integer`

and `Long`

extend `Number`

. For example you can use a wildcard type for the list element type:

`public static long total(List<? extends Number> list) {`

long sum = 0;

for (Number n : list) {

sum += n.longValue();

}

return sum;

}

This only works for the integral types however, since the `sum`

variable and the return value are of type `long`

.

Ideally you would like to be able to also use the method with `Float`

s and `Double`

s and return an object of the same type as the list element type, but this is not easy to do for two reasons:

- The only thing you can do with a
`Number`

is to get its value as one of the primitive number types. You can not sum two of them in a number dependent way. - It is not possible to create a 0-object of the right class.

You can use Java´s generics for this

`public <T extends Number> T total(List<T> list) {`

T sum = 0;

for (T n : list) {

sum += n.longValue();

}

return sum;

}

Knowing that `T`

will always be a `Number`

, things are simplified. However, this solution could work also for `String`

s, if necessary. The only change would be in the `extends`

part.

You can also use streams in Java 8

`public static <T extends Number> long sumList(List<T> list)`

{

return list.stream().mapToLong(a -> a.longValue()).sum();

}