我想了解更多有关如何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()'。 –