zoukankan      html  css  js  c++  java
  • 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<String> jdks = Arrays.asList("JDK6", "JDK8", "JDK10");

     2、匿名内部类

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

     3、JDK8 stream

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

     4、JDK9 List.of

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

     5、Collection 工具类应用

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

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

    三、Map 初始化

     1、匿名内部类

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

     2、java9 新特性

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

     3、使用 Guava

    Map<String, Integer> myMap = ImmutableMap.of("a", 1, "b", 2, "c", 3); 
  • 相关阅读:
    TCP 基础知识
    Spring Boot 实战 —— 日志框架 Log4j2 SLF4J 的学习
    MySQL 实战笔记
    Java 基础
    RPM 包的构建
    RPM 包的构建
    9. 桶排序
    8. 基数排序
    7. 计数排序
    6. 快速排序
  • 原文地址:https://www.cnblogs.com/liang1101/p/14783263.html
Copyright © 2011-2022 走看看