【问题标题】:Accessing variable in an ArrayList Object - Type class getter not working访问 ArrayList 对象中的变量 - 类型类 getter 不起作用
【发布时间】: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&lt;ResultsEntry&gt; 定义getCount。

我的理解是 ArrayList 会继承该类型类的方法。对这里发生的事情有任何见解吗?

【问题讨论】:

  • “我的理解是 ArrayList 将继承该类型类的方法” - 你的意思是你的 ResultsEntry 类?不,绝对不是。我怀疑你想要results.get(i).getCount()

标签: java class inheritance arraylist types


【解决方案1】:

你的理解不正确。 ArrayList 包含ResultsEntry 的实例,我相信您想为给定索引i 获取ResultsEntry 的元素,然后在该实例上调用getCount()。喜欢,

int count = results.get(i).getCount();

而且,如果您使用的是 Java 8+,则您的整个方法可以替换为 lambda、映射和对 sum 的调用。喜欢

return results.stream().mapToInt(ResultsEntry::getCount).sum();

【讨论】:

    【解决方案2】:

    你首先需要先从arraylist中获取项目

    .getCount();
    

    否则代码应该如何知道您定位到列表中的哪个项目

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-08
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 2021-05-05
      • 1970-01-01
      • 2023-03-15
      • 2020-01-12
      相关资源
      最近更新 更多