0

I have ArrayList as "deletedPositions", and im passing Value into that arrayList, before that i want to check wheather value is present in that array, if yes then i want delete that value, if not present , then add the value in that array List, How this CAn be done?

I tried with this code, but unable to get answer,

        if(deletedPositions.isEmpty())
    {
        deletedPositions.add(PositionChecked);
        Toast.makeText(getApplicationContext(), "Is empty ="+this.deletedPositions.size(), 1).show();
    }
    else
    {
        for(int i=0;i<deletedPositions.size();i++)
        {
            if(deletedPositions.get(i) == PositionChecked)
            {
                deletedPositions.remove(i);
                Toast.makeText(getApplicationContext(), "After removeArray ="+this.deletedPositions, 1).show();
            }
            else
            {
                deletedPositions.add(PositionChecked);
                Toast.makeText(getApplicationContext(), "After Added Array ="+this.deletedPositions, 1).show();
            }
        }
    }

Anyone help me to overcome this.. Thanks in advance,

1 Answer 1

1

You have to use the arraylist.contains method to check if the element is already present in the arraylist. You donot need a for loop to run through the entire arraylist. Use the following :

if(deletedPositions.contains(PositionChecked)) {
    int numIndex = deletedPositions.indexOf(PositionChecked)  
    deletedPositions.remove(numIndex);  
}
else {
    deletedPositions.add(PositionChecked);
} 

Also you can refer the following thread Check if a value exists in ArrayList

Sign up to request clarification or add additional context in comments.

3 Comments

I tried with this, theres no problem in adding, but while removing , error occurs..
what exactly does your code look like when you tried with this method ? and what error are you getting ?
YOur code help me get it out the expected output. thanks. but small change is there.

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.