eeijlar
eeijlar

Reputation: 1342

Method to calculate average from ArrayList<Float> and ArrayList<Integer>

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

Answers (3)

JB Nizet
JB Nizet

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

Damiano
Damiano

Reputation: 370

You could use a method declaration like that:

public Number average(Collection<? extends Number> values)
{
...    
}

Upvotes: 2

anubhava
anubhava

Reputation: 785196

Change signature to accept:

List<? extends Number>  

instead like this:

public Double avg(List<? extends Number> list) {
    // calculate average here
}

Upvotes: 4

Related Questions