【问题标题】:Alternative to ForEach?ForEach 的替代品?
【发布时间】:2013-01-12 11:53:44
【问题描述】:

我的班级考试具有以下属性:

package logic;

import java.util.ArrayList;

public class Exam {

    private int number;
    private Professor professor;
    private ArrayList<Question> questions = new ArrayList<Question>();
    private ArrayList<Test> tests = new ArrayList<Test>();

    ... // getters, setters, etcetera

}

我的问题是关于构造函数的:

public Exam(Professor professor, ArrayList<Question> questions) {

    this.professor = professor;

    for(Question question : questions) // <---
        this.questions.add(question); // <---

}

为了添加问题,是否有任何替代 foreach 的方法?例如,使用一段时间或另一个循环?怎么会这样?我一直在尝试,但无法成功。

【问题讨论】:

  • 我尝试使用一段时间和一个迭代器,但它变得有点乱......

标签: java foreach while-loop cycle


【解决方案1】:

简单的List#addAll()怎么样?

this.questions.addAll(questions);

请注意,如果您解释了为什么您当前的代码不适合您,以及 如何它会失败(编译错误?运行时异常?其他原因?) .

【讨论】:

  • 非常感谢,这真的帮了我很大的忙...实际上代码工作正常,但我必须找到另一种方法来做它作为练习请求。
【解决方案2】:
  1. Constructor

    this.questions = new ArrayList(questions);

  2. List#addAll

    this.questions.addAll(questions);

  3. 作业

    this.questions = 问题;

【讨论】:

    【解决方案3】:
    // assign the passed ArrayList to the class attribute
    this.questions = questions;
    

    【讨论】:

      猜你喜欢
      • 2020-09-15
      • 2017-11-09
      • 1970-01-01
      • 1970-01-01
      • 2018-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      相关资源
      最近更新 更多