在遍历集合元素的时候,传统上可以使用迭代器或者一般for循环进行遍历。但是传统for循环需要知道数组大小的限制。而且有些哈希表,list 并没有顺序可研,故考虑使用增强for循环。增强for循环再内部也是使用迭代器来实现。增强for循环的一般写法有:
@Test
public void test1(){
int a[]={1,2,3,4,5};
for(int i:a){
System.out.println(i);
}
}
增强for循环特点不需要知道具体集合大小,就可以遍历其中所有元素,并且可有效防止越界。增强for循环只能遍历实现Iterable 接口的类型。如下图所述:
在传统迭代器中遍历的方法中我们是采用如下的遍历方法:
public void Test4{
Map m=new HashMap();
m.put("111","abc");
m.put("222","bcd");
m.put("333","efg");
Set s=m.entrySet(); //获取Map的 (键-值)集合。
Iterator it=s.iterator(); //将(键-值)集合进行遍历。
while(it.hasNext()){
Map.Entry me=(Map.Entry)it.next();
}
}
现在我们可以采用新的增强for循环方式来遍历整个数组:
public void Test3()
{
Map m=new HashMap();
m.put(1,"liuyang");
m.put(2,"wangli");
m.put(3,"panlin");
Set s=m.entrySet(); //set 集合终不能有各个元素的值不能相等。
for(Object o:s){
Map.Entry me=(Map.Entry)o; //获得单个map中(键-值)的实体 ,Map.Entry是一个静态类。
System.out.println(me.getKey()+""+me.getValue());
}
}