【问题标题】:How to call the constructor with the next element of an ArrayList如何使用 ArrayList 的下一个元素调用构造函数
【发布时间】:2019-09-26 00:57:32
【问题描述】:

在调用构造函数时,我需要使用 ArrayList 中的下一个元素来创建对象

public class MinionToy implements ISurprise {

    private static final ArrayList<String> arrMinion = new ArrayList<String>(
            Arrays.asList("Dave", "Carl", "Kevin", "Stuart", "Jerry", "Tim"));

    private static int currentToyIndex = 0;

    private String surpriseName;

    private MinionToy(String minionName) {
        this.surpriseName = minionName;
    }

    public static MinionToy generate() {

        if (currentToyIndex < arrMinion.size()) {
            return new MinionToy(arrMinion.get(currentToyIndex));

        } else {
            currentToyIndex = 0;
        }
        currentToyIndex++;
        return new MinionToy(arrMinion.get(currentToyIndex));

    }

    @Override
    public void enjoy() {
        System.out.println("You have received the minion named: " + this.surpriseName);
    }
}

创建对象时,应始终使用下一个名称创建它。相反,它只是创建了 Dave、Dave 等

【问题讨论】:

标签: java


【解决方案1】:

问题是你永远不会增加玩具索引:

 public static MinionToy generate() {

        // if (0 < 4)
        //   return a new miniontoy(arra.get(0)
        // the rest of the code never gets executed.
        if (currentToyIndex < arrMinion.size()) {
            return new MinionToy(arrMinion.get(currentToyIndex));

        } else {
            currentToyIndex = 0;
        }
        currentToyIndex++;
        return new MinionToy(arrMinion.get(currentToyIndex));

尝试:

 public static MinionToy generate() {

        if (currentToyIndex >= arrMinion.size()) {
            currentToyIndex = 0;
        }
        return new MinionToy(arrMinion.get(currentToyIndex++));
 }

还有另一个使用模运算符 (%) 的答案已被删除。由于@Bogdan 也喜欢这个答案,所以我在这里添加了一个变体:

 private static currentToyIndex = -1;      // Important that we start at =1 so that we can get the zero'th element
  public static MinionToy generate() {
    return new MinionToy(arrMinion.get(++currentToyIndex % arrMinion.size());
  }

【讨论】:

  • 对 OP:currentToyIndex++ 的备注将在传递给 get() 方法后增加值。否则currentToyIndex 可能等于 size() 并导致 ArrayIndexOutOfBoundException。
  • @conffusion。您对 currentToyIndex++ 的看法是正确的。但是,if 语句可以防止出现异常的可能性。在 generate 方法从 arrayList 返回最后一个元素后,由于 ++,currentToyIndex 将变为 6(即现在 = arrMinion.size)。下次调用 generate 方法时,if 语句将是: if (index /* i.e. 6 / == size / Also = 6 */) 为真。因此,在此后续调用中,索引将重置回 0。因此不应出现任何异常。
  • 在生成方法的原始版本中,currentToIndex 在调用 get() 之前增加,但在测试之后因此存在潜在错误。但是你的代码是正确的。
  • @Conffusion,哦,我指的是 OP。 OP 中的另一个潜在问题是,如果通过 else 以某种方式将索引设置为 0,则索引将立即增加到 1。因此,第 0 个元素(“Dave”)永远不会成为“MinionToy”。这对戴夫来说可能是个好消息——没有人想成为小黄人的玩具! :-)
  • @Bogdan_Buzaianu 如果这对您有所帮助,您能否通过单击答案顶部旁边的灰色小勾来接受答案?
猜你喜欢
  • 2011-02-12
  • 2020-08-25
  • 2010-09-22
  • 2011-03-24
  • 1970-01-01
  • 2012-07-28
  • 1970-01-01
相关资源
最近更新 更多