java 高级for循环

格式:

for(数据类型 变量名: 被遍历的集合(Collection)或者数组)

只能取出,不能增删。

对集合进行遍历:只能获取集合元素。但是不能对集合进行操作。

迭代器除了遍历还能进行remove集合中元素的动作。

如何使用ListIterator还可以在遍历过程中对集合进行增删改查的动作。

传统for与高级for区别:

高级for有一个局限性。必须有被遍历的目标。

建议在遍历数组的时候,还是使用传统for。因为传统for可以定义角标。

public class ForDemo {
    public static void main(String[] args) {
        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());
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/hongxiao2020/p/12670805.html