Interator是对 collection 进行迭代的迭代器
package com.maya.test; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class TestIterator { public static void main(String[] args) { List<String> list = new ArrayList<String>(); for(int i=0;i<10;i++) { list.add("String"+i); } /* for(int j=0;j<list.size();j++) { if(j==5) { list.remove(j); } System.out.println(list.get(j)); }*/ /* for(String s : list) { if("String5".equals(s)) { list.remove(s); } System.out.println(s); }*/ /* for(Iterator<String> iter = list.iterator(); iter.hasNext(); ) { System.out.println(iter.next()); }*/ Iterator<String> iterWhile = list.iterator(); while(iterWhile.hasNext()) { String s = iterWhile.next(); if("String5".equals(s)) { iterWhile.remove(); } System.out.println(s); } System.out.println(list); } }
Interator运用的时候要注意它指向的目标,尤其在remove的时候
时间: 2024-10-30 14:51:38