之前集合的很多内容,实在是太难。自己总结不好,还是看看别人的博客吧。
https://blog.youkuaiyun.com/zhzh402/article/details/79670509
https://blog.youkuaiyun.com/weixin_34353714/article/details/85843856?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task
回归正题,增强for循环
格式:
for (数据类型变量名:被变量的集合(collection)或者数组)
{
}
对集合进行遍历。
只能获取集合元素。但是不能对集合进行操作。
迭代器除了遍历,还可以进行remove集合中元素的动作。
如果是用ListIterator,还可以在遍历过程中进行对集合增删改查的动作。
高级for循环有一个局限性:必须要有被遍历的目标。建议在遍历数组时还是尽量使用传统for循环,因为数组有角标。
例子:
ArrayList<String> a1=new ArrayList<String>();
a1.add("abc1");
a1.add("abc2");
a1.add("abc3");
for (String s:a1)
{
System.out.println(s);
}
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(1,"a");
hm.put(2,"b");
hm.put(3,"c");
Set<Integer> keySet=hm.keySet();
for (Integer i:keySet)
{
System.out.println(i+"::"+hm.get(i));
}
for (Map.Entry<Integer,String> me:hm.entrySet())
{
System.out.println(me.getKey()+"::"+me.getValue());
}