zoukankan      html  css  js  c++  java
  • Java中List与Map初始化的一些写法

    Java的在还没有发现新写法之前时,我一直是这么初始化List跟Map:

     代码如下 复制代码
     //初始化List
        List<string> list = new ArrayList</string><string>();
        list.add(www.111cn.net);
        list.add("string2");
        //some other list.add() code......
        list.add("stringN");
        
        //初始化Map
        Map</string><string , String> map = new HashMap</string><string , String>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        //.... some other map.put() code
        map.put("keyN", "valueN");
        </string>
     

    好麻烦啊。。。。。有一天撸到这样的一种方式:

     代码如下 复制代码
        //初始化List
        List<string> list = new ArrayList</string><string>(){{
        add("string1");
        add("string2");
        //some other add() code......
        add("stringN");
        }};
        
        //初始化Map
        Map</string><string , String> map = new HashMap</string><string , String>(){{
        put("key1", "value1");
        put("key2", "111cn.Net");
        //.... some other put() code
        put("keyN", "valueN");
        }};
        </string>
     

    虽然看起来没少写多少代码,但是个人觉得这种方式还是简洁多了很多,很流畅啊哈哈~

    例,后现一聚小编测试了List两个实例更简单


    法一:

    利用Array与ArrayList的相互转换方法,代码如下:

     代码如下 复制代码
    ArrayList<String> list = new ArrayList(Arrays.asList("Ryan", "Julie", "Bob"));
     

    法二:

    利用ArrayList的add方法完成初始化赋值,代码如下:

     代码如下 复制代码
    List list = new ArrayList<String>(){{
    add("A");
    add("B");
    }}
     

    更多详细内容请查看:http://www.111cn.net/jsp/Java/56734.htm

  • 相关阅读:
    nodejs中处理回调函数的异常
    Web前端开发十日谈
    Android 高仿微信6.0主界面 带你玩转切换图标变色
    Android EventBus源码解析 带你深入理解EventBus
    Android EventBus实战 没听过你就out了
    究竟谁在绑架中国的4G政策?
    Android 实战美女拼图游戏 你能坚持到第几关
    oracle学习
    his使用-重置密码
    oracle中的DDL、DML、DCL
  • 原文地址:https://www.cnblogs.com/alibai/p/3510066.html
Copyright © 2011-2022 走看看