数组遍历 和 迭代器遍历的区别
来源:互联网 发布:薛之谦淘宝店不开了吗 编辑:程序博客网 时间:2024/05/16 04:44
循环数组时候如果要对数组进行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<E> lastNext = lastReturned.next; try { LinkedList.this.remove(lastReturned); } catch (NoSuchElementException e) { throw new IllegalStateException(); } if (next==lastReturned) next = lastNext; else nextIndex--; lastReturned = header; expectedModCount++; }
阅读全文
0 0
- 数组遍历 和 迭代器遍历的区别
- js遍历数组和遍历对象的区别
- js遍历数组和遍历对象的区别
- js遍历数组和遍历对象的区别
- js数组遍历和对象遍历的区别
- JS中遍历普通数组和字典数组的区别
- JS中遍历普通数组和字典数组的区别
- 集合Set迭代器遍历和数组遍历
- js中遍历数组和对象的区别
- 数组的引用和遍历
- js---原生JS数组arr遍历方法forEach()和map()遍历的区别以及兼容写法
- 数组遍历for与foreach的区别
- 数组元素的赋值和遍历数组
- js中for遍历数组和对象,及对象和数组之间的区别
- 数组和遍历
- 数组和遍历器
- Unity3D数组和遍历
- 数组和遍历器
- 官方及自定义线程池
- Remove Duplicates from Sorted Array [python解]
- 列向量和行向量看待矩阵乘法
- Bayes公式解释
- hdu 2433 Travel(Dijkstra+思维)
- 数组遍历 和 迭代器遍历的区别
- python_yield
- 部署zinnia的问题
- 剪切子文件夹下的文件到当前文件夹的bat文件
- 遇到org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: java.sql.
- javascript基础—事件兼容EventUtil.js
- java 下载文件功能实现
- cordova device-motion插件
- 程序员面试金典: