ArrayIndexOutOfBoundsException when using the ArrayList's iterator

后端 未结 8 1191
甜味超标
甜味超标 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:02

    You could also do a for loop as you would for an array but instead of array[i] you would use list.get(i)

    for (int i = 0; i < list.size(); i++) {
        System.out.println(list.get(i));
    }
    
    0 讨论(0)
  • 2020-12-02 07:13

    While I agree that the accepted answer is usually the best solution and definitely easier to use, I noticed no one displayed the proper usage of the iterator. So here is a quick example:

    Iterator<Object> it = arrayList.iterator();
    while(it.hasNext())
    {
        Object obj = it.next();
        //Do something with obj
    }
    
    0 讨论(0)
  • 2020-12-02 07:13

    Efficient way to iterate your ArrayList followed by this link. This type will improve the performance of looping during iteration

    int size = list.size();
    
    for(int j = 0; j < size; j++) {
        System.out.println(list.get(i));
    }
    
    0 讨论(0)
  • 2020-12-02 07:16

    Apart of larsmans answer (who is indeed correct), the exception in a call to a get() method, so the code you have posted is not the one that is causing the error.

    0 讨论(0)
  • 2020-12-02 07:20

    Am I doing that right, as far as iterating through the Arraylist goes?

    No: by calling iterator twice in each iteration, you're getting new iterators all the time.

    The easiest way to write this loop is using the for-each construct:

    for (String s : arrayList)
        if (s.equals(value))
            // ...
    

    As for

    java.lang.ArrayIndexOutOfBoundsException: -1

    You just tried to get element number -1 from an array. Counting starts at zero.

    0 讨论(0)
  • 2020-12-02 07:21
    List<String> arrayList = new ArrayList<String>();
    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.

    0 讨论(0)
提交回复
热议问题