Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems finding median of arrayList

I keep getting The type of the expression must be an array type but it resolved to ArrayList<Double> The arrayList is pulling numbers from my Test class. I made the if to determine if the arrayList has an even amount of values in it or an odd, for I could use the two different ways to determine the median. But I'm not able to get the median formula to work.

public class Data {

private ArrayList<Double> sets;

public Data(double[] set) {
    this.sets = new ArrayList<Double>();
    for (double i : set) {
        this.sets.add(i);
    }
}

public double getMedian(){
    Collections.sort(sets);

    double middle = sets.size()/2;
        if (sets.size()%2 == 1) {
           middle = (sets[sets.size()/2] + sets[sets.size()/2 - 1])/2;
        } else {
            middle = sets[sets.size() / 2];
        }
      return middle;
}
like image 373
JavaNewbie42 Avatar asked May 05 '26 01:05

JavaNewbie42


1 Answers

The problem is on the line where you find the middle:

middle = (sets[sets.size()/2] + sets[sets.size()/2 - 1])/2;

You can use [index] notation only with arrays. You need to use getter/setter methods to access the elements of an ArrayList. This should work:

middle = (sets.get(sets.size()/2) + sets.get(sets.size()/2 - 1))/2;
like image 153
salix Avatar answered May 06 '26 15:05

salix