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

  • 相关阅读:
    更改ubuntu的官方镜像源
    python中的decorator的作用
    thunderbird 设置 邮件回复时内容在上方显示
    Sapnco3 RfcTable Structure
    DbEntry 访问Access2010数据库
    DbEntry 默认 主键ID为long
    DbEntry 简单实现
    nginx学习时使用EditPuls编辑conf.xml
    java的集合类面试题
    tomcat组成介绍和调优方案
  • 原文地址:https://www.cnblogs.com/alibai/p/3510066.html
Copyright © 2011-2022 走看看