ArrayIndexOutOfBoundsException when using the ArrayList's iterator

后端 未结 8 1213
甜味超标
甜味超标 2020-12-02 06:36

Right now, I have a program containing a piece of code that looks like this:

while (arrayList.iterator().hasNext()) {
     //value is equal to a String value         


        
8条回答
  •  不知归路
    2020-12-02 07:21

    List arrayList = new ArrayList();
    for (String s : arrayList) {
        if(s.equals(value)){
            //do something
        }
    }
    

    or

    for (int i = 0; i < arrayList.size(); i++) {
        if(arrayList.get(i).equals(value)){
            //do something
        }
    }
    

    But be carefull ArrayList can hold null values. So comparation should be

    value.equals(arrayList.get(i))
    

    when you are sure that value is not null or you should check if given element is null.

提交回复
热议问题