Skip to content
Advertisement

Java Generics and adding numbers together

I would like to generically add numbers in java. I’m running into difficulty because the Numbers class doesn’t really support what I want to do. What I’ve tried so far is this:

JavaScript

Obviously this will not work. How can I go about correcting this code so I could be given a list of <int> or <long> or whatever and return the sum?

Advertisement

Answer

In order to calculate a sum generically, you need to provide two actions:

  • A way to sum zero items
  • A way to sum two items

In Java, you do it through an interface. Here is a complete example:

JavaScript
Advertisement