我面临以下问题,这是一个测验(随机回答,每个问题的答案不尽相同):
我有两个列表listOfAnswers
和listOfUserAnswers
(均为类型List<Answer>
)。Answer
的定义如下:
public class Answer {
int answerId;
int answerIsCorrect;
String answer;
public Answer() {
}
public void setId(int id) {
this.answerId = id;
}
public Answer setAnswer(String answer) {
this.answer = answer;
return this;
}
public void setAnswerIsCorrect(int answerIsCorrect) {
this.answerIsCorrect = answerIsCorrect;
}
public int getId() {
return this.answerId;
}
public String getAnswer() {
return this.answer;
}
public int getAnswerIsCorrect() {
return this.answerIsCorrect;
}
public String toString() {
return String.format("Answer[%s, %s, %s]", this.answerId, this.answerIsCorrect, this.answer);
}
}
listOfAnswers
对象保存每个问题的每个答案(在listOfQuestions
类型的List<Question>
中指定,但这不是问题)。listOfUserAnswers
对象保存每个答案,用户已选择(通过复选框选择)。此时,应用程序不知道用户选择的答案是对还是错。现在,在计算结果时,我要遍历
listOfAnswers
,然后检查listOfAnswers.get(i).getId()
中是否还可以使用answerId(listOfUserAnswers
)。但这如何工作?我认为我无法与
listOfUserAnswers.contains(...)
核对。还是我错了?如果您无法理解,请发表评论。
最佳答案
您无法检查listOfUserAnswers.contains()
,因为尚未定义Answer.equals()
方法。您必须像这样遍历两个列表:
for(Answer answer : listOfAnswers) {
for(Answer userAnswer : listOfUserAnswers) {
if(answer.getId() == userAnswer.getId()) {
//answer matches
}
}
}
另外,您可以定义一个
Answer.equals()
方法:@Override
public boolean equals(Object obj) {
return obj instanceof Answer && ((Answer)obj).answerId == this.answerId;
}
现在,您可以执行以下操作,而不是嵌套循环:
for(Answer answer : listOfAnswers) {
if(listOfUserAnswers.contains(answer) {
//answer matches
}
}
编辑:如注释中所述,您应该在覆盖
hashCode()
时始终覆盖equals()
。在这种情况下,最简单的实现是:@Override
public int hashCode() {
return answerId;
}