[英]Java: Referencing array from ArrayList as method input
我在使用下面的 Java 時遇到了問題。 data_array
是數組的 ArrayList。 我正在嘗試使用“for”循環訪問 ArrayList 中的所有數組,但由於某種原因我無法在 ArrayList 上執行.get
。 任何幫助將非常感激! 謝謝!
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;
}
關於它為什么不能編譯有幾個問題(至少)。
首先是沒有Collection.get
方法。 而不是采用Collection<Double>
,而是采用List<Double>
(ArrayList 符合 List)。
當這個問題解決后,下一個問題是List<Double>.get(int) => Double
,但holding
是double[]
所以分配是無效的。
i in [0, avg_bar)
循環i in [0, avg_bar)
但使用data_array.get(i)
也是可疑的; 這是無效索引的秘訣。 雖然這可以通過刪除get(i)
並循環迭代器來解決。
無論如何,我懷疑一個大問題是計算SMA 的算法不正確。 考慮刪除holding[]
數組變量並在計算總和時直接使用每個data_array 值(P_n、P_n-1 等)。
您不能執行 .get 方法,因為您要求的是“集合”而不是“列表”
'Collection' 是一個高於 List 的接口,它沒有 get 方法。 如此處所示-> http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
改用列表。
或者(您不應該)將集合轉換為數組。
接口Collection
本身沒有.get()
方法。
請參閱http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
您可以檢查您是否正在傳遞實現 Collection 的類之一, .get()
具有.get()
方法,例如ArrayList
,然后對其進行轉換。
否則,您可以使用data_array.iterator()
並使用它來遍歷集合以訪問每個項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.