4

I have one Array List and contains some values like 2,3,4,5,6. now how to check if the value is present and want to delete that particular Value. please help me to do this. tnx in advance.

I tried ,

ArrayList<Integer> Positions=new ArrayList<Integer>();
Positions.remove(6);

but it shows an error.

4
  • here 6 is int and ArrayList is of Integer type . also you can try Positions.contains(Integer(6)); Commented Oct 5, 2012 at 6:33
  • Yes , i tried Positions.contains(Integer(6)); and its working, but how to delete that 6 from Array? Commented Oct 5, 2012 at 6:36
  • do it this way. if (Positions.contains(Integer(6))){Positions.remove(Integer(6));} Commented Oct 5, 2012 at 6:37
  • And please god, learn the naming convention... Capital letter for class/project names. NOT FOR VARIABLES (like Positions should be positions) Take a look here: slideshare.net/Shaon_sikdar/android-code-convention Commented Oct 5, 2012 at 6:44

2 Answers 2

8

Positions.remove(6); delete the item from particular position.

So first you have to compare the item in arraylist using for loop and get the position of that item and call Positions.remove(that Item Position in ArrayList).

Try this code.

ArrayList<Integer> positions = new ArrayList<Integer>();
positions.add(3); // add some sample values
positions.add(6); // add some sample values
positions.add(1); // add some sample values
positions.add(2); // add some sample values
positions.add(6);

for(int i=0;i<positions.size();i++)
{
    if(positions.get(i) == 6)
    {
        positions.remove(i);
    }
}

Log.i("========== After Remove ",":: "+positions.toString());

Output : I/========== After Remove ( 309): :: [3, 1, 2]

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

4 Comments

tnx Chirag, Can u help me how to get an Items Position?
yeah nice Chitag Raval, now its Working.. :)
i thought that its possible to Accept both the answer, and made tick in second.and i dont know that first answer is unchecked.
how to add a new item if its not there in array?
5

Try this:

ArrayList<Integer> positions = new ArrayList<Integer>();
positions.add(3); // add some sample values
positions.add(6); // add some sample values
positions.add(1); // add some sample values
positions.add(2); // add some sample values
int index = positions.indexOf(6); // finds the index of the first occurrence of 6
if (index >= 0) { // if not found, index will be -1
    positions.remove(index); // removes this occurrence
}

2 Comments

But what if there are more than one 6 in list ?
Then you would use a while loop to repeat the above until the index is -1.

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.