数组遍历 和 迭代器遍历的区别

循环数组时候如果要对数组进行add、remove操作,采用 迭代器的遍历,

list的遍历通常有三种方式:

1,普通的数组遍历

 for (int i = 0; i < args.length; i++) {

    }

2,加强型数组遍历

for (String string : args) {

    }

3,迭代器遍历

while (it.hasNext()) {
            type type = (type) it.next();

    }
使用数组遍历的过程中不能进行add、remove等改变数组内容的操作,否则会报错;
迭代器可以

final void checkForComodification() {
    if (modCount != expectedModCount)
    throw new ConcurrentModificationException();
}

因为

array进行add、remove等操作时,array中index后的元素会产生移动

public void add(int index, E element) {
    if (index > size || index < 0)
        throw new IndexOutOfBoundsException(
        "Index: "+index+", Size: "+size);

    ensureCapacity(size+1);  // Increments modCount!!
    System.arraycopy(elementData, index, elementData, index + 1,
             size - index);
    elementData[index] = element;
    size++;
    }
/*
     * Private remove method that skips bounds checking and does not
     * return the value removed.
     */
    private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // Let gc do its work
    }

LinkedList内部类 public ListIterator listIterator(int index)

    public E next() {
        checkForComodification();
        if (nextIndex == size)
        throw new NoSuchElementException();

        lastReturned = next;
        next = next.next;
        nextIndex++;
        return lastReturned.element;
    }
public void add(E e) {
        checkForComodification();
        lastReturned = header;
        addBefore(e, next);
        nextIndex++;
        expectedModCount++;
    }
public void remove() {
            checkForComodification();
            Entry lastNext = lastReturned.next;
            try {
                LinkedList.this.remove(lastReturned);
            } catch (NoSuchElementException e) {
                throw new IllegalStateException();
            }
        if (next==lastReturned)
                next = lastNext;
            else
        nextIndex--;
        lastReturned = header;
        expectedModCount++;
    }

你可能感兴趣的:(javaAndAndroid,Android基础知识)