Reputation: 21
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
Reputation: 14281
this.questions = new ArrayList(questions);
this.questions.addAll(questions);
Assignment
this.questions = questions;
Upvotes: 2
Reputation: 168845
// assign the passed ArrayList to the class attribute
this.questions = questions;
Upvotes: 1
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