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

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

     代码如下 复制代码
     //初始化List
        List<string> list = new ArrayList</string><string>();
        list.add("string1");
        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", "value2");
        //.... 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

  • 相关阅读:
    菜鸟看懂算法以后之一:头痛的64次左移
    C语言通过指针数组和二维数组读取文件
    C++中构造函数调用构造函数
    bnuoj53075 外挂使用拒绝
    [CodeForces]String Reconstruction
    BNU-2017.7.4排位赛2总结
    BNU-2017.7.5排位赛3总结
    BNU-2017.7.3排位赛1总结
    微软大楼设计方案(困难)
    最长公共子序列针对小字符集的算法
  • 原文地址:https://www.cnblogs.com/alibai/p/3523517.html
Copyright © 2011-2022 走看看