我想了解更多有關如何ArrayList類型工作時使用自定義類,並遇到一個問題,我不太明白。我有public方法設置在我的類型類中,但在爲我的ArrayList調用它們時無法讓它們工作。下面是類的簡化版本:在一個ArrayList對象中訪問變量 - 類型的類getter不工作
public class ResultsEntry {
//Create instance private variables count (int) and target (char)
private Integer count;
private char target;
//Create a single constructor with the two values
public ResultsEntry (Integer count, char target)
{
this.count = count;
this.target = target;
}
//Public get methods for count and target
public Integer getCount()
{
return count;
}
public char getTarget()
{
return target;
}
//Public toString method that returns a string in the format <target, count>
public String toString() {
return ("<" + target + ", " + count + ">");
}
}
那麼接下來類:
import java.util.ArrayList;
public class SharedResults {
//Create private instance variable - results (ArrayList of ResultsEntry type)
private static ArrayList<ResultsEntry> results = new ArrayList<ResultsEntry>();
//A default constructor that initializes the above data structure
public SharedResults (Integer resultsCount, char resultsTarget)
{
Integer sharedResultsCount = resultsCount;
char sharedResultsTarget = resultsTarget;
results.add(new ResultsEntry(sharedResultsCount, sharedResultsTarget));
}
/*
* getResult method with no arguments returns sum of the count entry values in the
* shared results data structure.
*/
public static Integer getResults()
{
Integer sum = 0;
for (int i = 0; i < results.size(); i++) {
System.out.println("getResults method input "+ results.(i));
Integer input = results.getCount(i);
sum = input + sum;
/*
*Some code here that adds new count results to the counts in all
*other array elements
*/
}
return sum;
}
}
我遇到的問題是,results.getCount(i);
讓getCount將不是爲ArrayList<ResultsEntry>
類型定義的錯誤。
我的理解是ArrayList會繼承類型的類的方法。深入瞭解這裏發生了什麼?
「我的理解是, ArrayList將繼承類型的類的方法「 - 你的意思是你的'ResultsEntry'類?不,絕對不是。我懷疑你想'results.get(i).getCount()'。 –