How to remove element from ArrayList by checking its value?

后端 未结 11 1198
一整个雨季
一整个雨季 2020-12-01 03:47

I have ArrayList, from which I want to remove an element which has particular value...

for eg.

ArrayList a=new ArrayList         


        
11条回答
  •  一生所求
    2020-12-01 04:05

    You would need to use an Iterator like so:

    Iterator iterator = a.iterator();
    while(iterator.hasNext())
    {
        String value = iterator.next();
        if ("abcd".equals(value))
        {
            iterator.remove();
            break;
        }
    }
    

    That being said, you can use the remove(int index) or remove(Object obj) which are provided by the ArrayList class. Note however, that calling these methods while you are iterating over the loop, will cause a ConcurrentModificationException, so this will not work:

    for(String str : a)
    {
        if (str.equals("acbd")
        {
            a.remove("abcd");
            break;
        }
    }
    

    But this will (since you are not iterating over the contents of the loop):

    a.remove("acbd");
    

    If you have more complex objects you would need to override the equals method.

提交回复
热议问题