今天说说集合的iterator迭代器与集合下标的使用
先上代码
import java.util.ArrayList; import java.util.Iterator; public class Test { public Test() { // 初始化List addItemToList(); } private ArrayList<String> list = new ArrayList<String>(); private void addItemToList() { for (int i = 0; i < 5; i++) { list.add(i + ""); } } public ArrayList<String> getList() { return list; } public void setList(ArrayList<String> list) { this.list = list; } public static void main(String[] args) { Test test1 = new Test(); ArrayList<String> test1List = test1.getList(); for (int i = 0; i < test1List.size(); i++) { // 这里使用下标,直接指向元素 test1List.remove(i); } System.out.println("test1List have been removed all elements"); Test test2 = new Test(); ArrayList<String> test21List = test2.getList(); for (Iterator<String> iterator = test21List.iterator(); iterator .hasNext();) { // 使用迭代器对集合操作时,需要先做next() // next()类似于游标,他是介于两个元素之间的 // 不像上面直接指向某个元素 iterator.next(); iterator.remove(); } System.out.println("test2List have been removed all elements"); } }
1.使用迭代器对集合操作时,需要先做next()
2.next()类似于游标,他是介于两个元素之间的,而下标,直接指向元素(详情看下图)
原文地址:http://blog.csdn.net/raylee2007/article/details/46560075