0

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.

10
  • 2
    Should that be an ArrayList<Long>? Commented Jun 30, 2014 at 12:57
  • I don't see where you used contains(). but still I would say: Why not use a set. And you have to use brackets with if-clauses. and you should define getters/setters. Commented Jun 30, 2014 at 12:57
  • 3
    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 - I've serious concerns about your design.. Commented Jun 30, 2014 at 12:58
  • 2
    With "long" instead of "Long", it shouldn't even compile. Commented Jun 30, 2014 at 12:59
  • 1
    contains() works just fine with your equals() implementation, as you can see here. Your problem must be elsewhere. Commented Jun 30, 2014 at 13:03

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

2 Comments

The answers.contains(10) was apparently some kind of typo, so this answer isn't really valid anymore.
I am using answers.contains(new Answer(10,20)) to see if the question_no 10 was already answered

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.