how to remove particular data from ArrayList<Integer> in android

扶醉桌前 提交于 2020-01-03 15:33:20

问题


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.


回答1:


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]




回答2:


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
}


来源:https://stackoverflow.com/questions/12740701/how-to-remove-particular-data-from-arraylistinteger-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!