【JAVA】语法记录

2019-06-29  本文已影响0人  躁动的中年大叔

1. 双括弧语法

        // 用于集合初始化
        List<String> list = new ArrayList<String>(){{
            add("dog");
            add("cat");
            add("monkey");
        }};

        Set<String> set = new HashSet<String>(){{
            add("cat");
            add("cat");
        }};

        Map<String, String> map = new HashMap<String, String>(){{
            put("name", "jim");
            put("age", "17");
        }};

2. foreach:增强for循环

本质上是使用了Iterator迭代器和do-while循环。
在foreach迭代中,如果对迭代集合做了增加元素、删除元素等操作的话,会抛出ConcurrentModificationException异常。

        for(String item: list){
            if(item.equals("dog")){
                list.remove(item);
            }
        }

未完待续

上一篇 下一篇

猜你喜欢

热点阅读