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,

Vishnu
  • 349
  • 3
  • 8
  • 16

1 Answers1

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

Community
  • 1
  • 1
Abhishek Sabbarwal
  • 3,758
  • 1
  • 26
  • 41