简体   繁体   中英

Java: Referencing array from ArrayList as method input

I'm having trouble with the Java below. data_array is an ArrayList of arrays. I'm trying to get to all of the arrays within the ArrayList with a 'for' loop but I cannot do .get on the ArrayList for some reason. Any help would be much appreciated! Thanks!

public static double calc_SMA (Collection<Double> data_array, int bar_avg, int array_position){

      //Create array to select which array in the ArrayList to pull from
      double [] holding = new double [4];

      //variable to hold the sum of the bars
      double sum = 0.0;

      //Create loop to pull data via...put into avg_calc
      for (int i = 0; i < bar_avg; i++) {

        //Cycle through arrays within the data_array ArrayList starting from first row to bar_avg - 1
        holding = data_array.get(i);

        //Add value to the previous value with 'sum'
        //array_position is the place (0-3) that we are calculating avg of 
        sum = sum + holding[array_position];

        //clear holding array
        holding = null;
      }

      double average = sum/bar_avg;
      return average;
  }

There are several problems (at least) as to why it won't compile.

The first is there is no Collection.get method . Instead of taking a Collection<Double> , take a List<Double> instead (an ArrayList conforms to List).

When that is resolved the next problem is List<Double>.get(int) => Double , but holding is double[] so the assignment is invalid.


It is also suspicious to loop i in [0, avg_bar) but use data_array.get(i) ; this is a recipe for an invalid index. While this could be fixed by dropping get(i) and looping an Iterator..

Anyway, I suspect a big problem is an incorrect algorithm to compute the SMA . Considering removing the holding[] array variable and use each data_array value (P_n, P_n-1, etc.) directly in calculating the sum.

You cannot do the .get method because you are asking for a 'collection' not for a 'List'

'Collection' is an interface higher then List and it does not have a get method. as seen here -> http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html

Use a List instead.

Or (you should not) cast the collection into an array.

The interface Collection itself does not have a .get() method.

See http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html

You could check that you are being passed one of the classes that implements Collection that has a .get() method, eg ArrayList and then cast it.

Otherwise you could use the data_array.iterator() and use that to iterate through the collection to access each of the items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM