• java中初始化list的几种方法


    java 8中初始化list的方法有以下几种:

            // 1 new ArrayList,依次添加元素,这种方式最常见,只是代码不够简洁
            List<Object> one = new ArrayList<>();
            one.add("1");
            one.add("2");
            System.out.println(one);
    
            // 2 Arrays.asList,一句话就能初始化,简洁。但是这种方式初始化的list是不可改变的,无法添加和删除
            List<Object> two = Arrays.asList("a","b","c");
            // two.add("d");
            // 如果想要可变,使用new ArrayList包装一下
            two = new ArrayList<>(Arrays.asList("aa","bb","cc"));
            two.add("dddd");
            System.out.println(two);
    
            // 3 {{}},匿名内部类的方式,这种方式降低了代码可读性,而且存在内存泄露的风险
            List<Object> three = new ArrayList<Object>(){{
                add("ni");
                add("wo");
                add("ta");
            }};
            three.add("women");
            System.out.println(three);
    
            // 4 stream,未免大材小用
            List<Object> four = Stream.of("ff","gg").collect(Collectors.toList());
            four.add("kk");
            System.out.println(four);
    // 1 new ArrayList,依次添加元素,这种方式最常见,只是代码不够简洁
    List<Object> one = new ArrayList<>();
    one.add("1");
    one.add("2");
    System.out.println(one);

    // 2 Arrays.asList,一句话就能初始化,简洁。但是这种方式初始化的list是不可改变的,无法添加和删除
    List<Object> two = Arrays.asList("a","b","c");
    // two.add("d");
    // 如果想要可变,使用new ArrayList包装一下
    two = new ArrayList<>(Arrays.asList("aa","bb","cc"));
    two.add("dddd");
    System.out.println(two);

    // 3 {{}},匿名内部类的方式
    List<Object> three = new ArrayList<Object>(){{
    add("ni");
    add("wo");
    add("ta");
    }};
    three.add("women");
    System.out.println(three);

    // 4 stream,未免大材小用
    List<Object> four = Stream.of("ff","gg").collect(Collectors.toList());
    four.add("kk");
    System.out.println(four);
  • 相关阅读:
    6、查看历史记录
    A Tour of Go Range
    Go Slices: usage and internals
    A Tour of Go Nil slices
    A Tour of Go Making slices
    A Tour of Go Slicing slices
    A Tour of Go Slices
    A Tour of Go Arrays
    A Tour of Go The new function
    A Tour of Go Struct Literals
  • 原文地址:https://www.cnblogs.com/mydesky2012/p/11199846.html
Copyright © 2020-2023  润新知