th3ramr0d th3ramr0d - 1 month ago 6
Android Question

Adding int to arraylist only if it does not already exist

I have

position
that is equal to which question is shown. I want to add an int equal to
position
to an arraylist. Then I want to check and see if that arraylist has that int within it to prevent that int being added again. With the following code it adds the
position
int multiple times.

if(correctQuestions.size() == 0){
correctQuestions.add(position);
}else if(correctQuestions.size() > 0){
if(!Arrays.asList(correctQuestions).contains(position)){
correctQuestions.add(position);
}
}


If
position = 0;
then each run of this code will continually add
position
to my arraylist regardless if 0 is in it or not. For instance running this code 3 times will result in my arraylist outputting [0,0,0] when it should only allow it to add 0 once.

Answer

you must write like this:

if(correctQuestions.size() == 0){
    correctQuestions.add(position);
}else if(correctQuestions.size() > 0){
    if(!correctQuestions.contains(position)){
        correctQuestions.add(position);
    }
}
Comments