因为最近通过遍历输出数组、集合和链表使用了扩展for循环,所以很简单。 我在这里做一个简单的记录
public class test1 { publicstaticvoidmain (字符串[ ] args ) arraylistintegerlist=new ArrayList ); list.add(1; list.add(2; for(intI:list ) system.out.println ) I; }}链表集合数组也可以同样通过for (元素型变量:对象名)进行遍历输出
增强for循环集合时,将自动使用迭代器
使用扩展for循环时,必须确定集合是否为空。 否则,将报告空指针异常
Map无法使用扩展for循环。 没有迭代器,使用entrySet ()进行迭代
Entry是一个键-值对对象,包含两个属性: key和value,可以从getKey (或getValue )检索value的值。 entrySet实现了一个用于遍历Map对象的Set接口。
@Testpublic void test () { Map map=new HashMap ); map.put(1,aaa ); map.put('2',' bbb ' ); map.put('3',' ccc ' ); 重复遍历//map集合的第二种方法Set set=map.entrySet (; Iterator it=set.iterator (; while(it.Hasnext () (输入项=)输入项) it.next ); stringkey=(string ) entry.getKey ); stringvalue=(string ) entry.getValue ); system.out.println(key'='value; }