Reputation: 1342
I have a Java method which takes an
ArrayList<Float>
as a parameter. It calculates the average of the ArrayList, and returns the value.
Now I want to pass an
ArrayList<Integer>
Java will not allow this, it would be possible in C++.
So, just wondering what alternatives there are available, other than creating an identical class which differs only by the type, of the arguments passed to each method.
Upvotes: 1
Views: 585
Reputation: 691755
Your method should take a List<? extends Number>
as argument, get the float value from the numbers and compute their average.
List<? extends Number>
means: a List of some unknown type being or extending Number.
Upvotes: 7
Reputation: 370
You could use a method declaration like that:
public Number average(Collection<? extends Number> values)
{
...
}
Upvotes: 2
Reputation: 785196
Change signature to accept:
List<? extends Number>
instead like this:
public Double avg(List<? extends Number> list) {
// calculate average here
}
Upvotes: 4