Home > Software design >  How to find the average of numbers in a generic class of Numbers in Java?
How to find the average of numbers in a generic class of Numbers in Java?

Time:10-29

I have created a generic class that creates an ArrayList of Numbers

public class MyMathClass<T extends Number> {
private ArrayList<T> myarraylist;

public MyMathClass(ArrayList<T> arrayList){
    myarraylist = arrayList;
}

I tried to create a method that basically calculates the average of the given ArrayList

public double average(){
    var average = 0;
    for(int i = 0 ; i <= myarraylist.size(); i  ){
        average  = myarraylist.get(i);
    }
}

but when try to add the average with the value at index i, I get this error: "operator cannot be applied to 'int' , 'T'

CodePudding user response:

It's relative to Unboxed Type and Box Type.

Refer here for more detail: What does it mean to say a type is "boxed"?

To make your code work, only need to convert Number to double and sum it.

Number num = myarraylist.get(i);
average  = num == null ? 0 : num.doubleValue();

CodePudding user response:

Number objects implement a doubleValue() method. Return the average of those:

public double average() {
    return myarraylist.stream().mapToDouble(Number::doubleValue).average().orElse(0);
}

The orElse(0) handles the list being empty.


Style note: Use the abstract type where possible, so prefer:

private List<T> myList;

public MyMathClass(List<T> list){
    myList = list;
}

See Liskov substitution principle.

  • Related