java 各类型初始化汇总


一、数组初始化

 1、静态初始化

int[] intArr = new int[]{1,2,3,4,5,9};

 2、简化静态初始化

String[] strArr = {"张三","李四","王二麻"};

 3、动态初始化

int[] price = new int[4];
price[0] = 99;
price[1] = 101;
......

二、List 初始化

 1、Arrays 工具类应用

List jdks = Arrays.asList("JDK6", "JDK8", "JDK10");

 2、匿名内部类

List names = new ArrayList<>() {{
    add("Tom");
    add("Sally");
    add("John");
}};

 3、JDK8 stream

List colors = Stream.of("blue", "red", "yellow").collect(toList());

 4、JDK9 List.of

List cups = List.of("A", "B", "C");

 5、Collection 工具类应用

  这种方式添加的是不可变的、复制某个元素N遍的工具类

List apples = Collections.nCopies(3, "apple");

三、Map 初始化

 1、匿名内部类

HashMap myMap  = new HashMap(){{  
      put("a","b");  
      put("b","b");       
}};

 2、java9 新特性

Map.of("Hello", 1, "World", 2);//不可变集合

 3、使用 Guava

Map myMap = ImmutableMap.of("a", 1, "b", 2, "c", 3);