I am using an ArrayList to save Questions and their answers. The ArrayList is made up of Answer Class which has Question No and an ArrayList of answers_marked as follows:
private class Answer {
private long question_no;
private ArrayList<long> answer;
public boolean equals(Object o) {
if (o instanceof Answer)
if (((Answer)o).question_no == this.question_no)
return true;
return false;
}
}
public ArrayList<Answer> answers = new ArrayList<Answer>();
Now, when the user changes his answer I want to look into the answers arraylist and check if the question_no already exists in the answers. If it does then update the answer value for which answer was changed. I am trying to use contains method to check if the question_no already exists, but it always return false. What am I doing wrong here? Which other data-structure would be best suited for to do this?
I am using answers.contains(new Answer(10,20)) to see if the question_no 10 was already answered.
if you have a ArrayList you shouldn't do answers.contains(10)
- this won't work.. 10 is an int and, in your equals()
, if o
is not an Answer
then you are returning false
.
Rather, try:
Answer answer1 = new Answer(1);
Answer answer2 = new Answer(2);
answers.add(answer1);
answers.contains(answer1) ;//= true
answers.contains(answer2) ;//= false
answers.contains(10) ;//= false
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.