[英]contains() method in ArrayList, Java
I am using an ArrayList to save Questions and their answers. 我正在使用ArrayList保存问题及其答案。 The ArrayList is made up of Answer Class which has Question No and an ArrayList of answers_marked as follows: ArrayList由具有问题编号的Answer类和一个Answers_mark的ArrayList组成,如下所示:
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. 现在,当用户更改其答案时,我想查看答案数组列表,并检查答案中是否已经存在question_no。 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. 我正在尝试使用contains方法来检查question_no是否已经存在,但是它总是返回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. 我正在使用answers.contains(new Answer(10,20))来查看question_no 10是否已经回答。
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
. 如果您有ArrayList,则不应执行answers.contains(10)
-这将无法工作。10是int,并且在equals()
,如果o
不是Answer
那么您将返回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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.