Pablo Stein
Pablo Stein

Reputation: 21

Alternative to ForEach?

I have the class Exam with the following attributes:

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

}

My question is about the constructor:

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

    this.professor = professor;

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

}

Is there any alternative to foreach in order to add the questions? For example, using a while or another cycle? How could it be? I've been trying but couldn't make it work.

Upvotes: 0

Views: 1087

Answers (3)

StarPinkER
StarPinkER

Reputation: 14281

  1. Constructor

    this.questions = new ArrayList(questions);

  2. List#addAll

    this.questions.addAll(questions);

  3. Assignment

    this.questions = questions;

Upvotes: 2

Andrew Thompson
Andrew Thompson

Reputation: 168845

// assign the passed ArrayList to the class attribute
this.questions = questions;

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 360066

How about a simple List#addAll()?

this.questions.addAll(questions);

Note, it would help if you explained why your current code is not working for you, and how it fails (compile error? runtime exception? something else?).

Upvotes: 3

Related Questions