【发布时间】:2018-01-19 00:02:05
【问题描述】:
我正在尝试更多地了解 ArrayList 类型在使用自定义类时是如何工作的,并且遇到了一个我不太了解的问题。我在我的类型类中设置了公共 get 方法,但是在为我的 ArrayList 调用它们时无法让它们工作。以下是这些类的简化版本:
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); 给出了一个错误,即未为类型ArrayList<ResultsEntry> 定义getCount。
我的理解是 ArrayList 会继承该类型类的方法。对这里发生的事情有任何见解吗?
【问题讨论】:
-
“我的理解是 ArrayList 将继承该类型类的方法” - 你的意思是你的
ResultsEntry类?不,绝对不是。我怀疑你想要results.get(i).getCount()。
标签: java class inheritance arraylist types