• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Spillage
博客园    首页    新随笔    联系   管理    订阅  订阅
List的初始化方式

在LinkedIn考试考到了,很遗憾没考过,特意记录一下,下次再战!
文章不是我写的,看到别人的总结,发在我这里自己看看

在 Java 中几种初始化 List 的方法:

1. 

List<String> stringList = new LinkedList<>();
stringList.add("a");
stringList.add("b");
stringList.add("c");

  这种方式简单粗暴好理解,比较花费代码行数,而且是各个JDK都支持的通用做法

2. 

List<String> stringList = new LinkedList<String>(){{
    add("a");
    add("b");
    add("c");
}};

  这里定义了一个匿名的内部类,并使用 add 来初始化,虽然可以写为一行(这里并不是很重要),匿名内部类有一些效率损失,其次,如果需要把类返回给外部使用,可能产生内存泄漏。

 

3.

List<String> stringList = Arrays.asList("a", "b", "c");

  这里使用了 asList 的静态方法,2中提到的两个风险都能避免,但同2一样,不支持删减,这点要注意。

      另外:

  • Arrays.asList 的参数如果是基本类型的数组时,需要留意返回值可能和你预期的不同。
      
int[] intArray = new int[]{1, 2, 3};
Integer[] integerArray = new Integer[]{1, 2, 3};
List<int[] > intArrayList = Arrays.asList(intArray);
List<Integer> integerList = Arrays.asList(integerArray);
List<Integer> integerList2 = Arrays.asList(1, 2, 3);

  也就是说,Arrays.asList(intArray) 返回的是 List<int> 不是 List<Integer>, 尽量使用包装类,避免使用底层数据结构。PS, {{}} 双括号语法同样可用于初始化 Map 等其他众多类型

 

4.

List<String> list = Stream.of("a", "b", "c").collect(Collectors.toList());

  这是 JDK8以后支持的方式,流式初始化,可以用流式处理的方法有很多,这里有点大材小用。

 

5.

List<String> list = Lists.newArrayList("a", "b", "c");

  这是 JDK9的初始化方式

posted on 2021-08-25 15:50  Spillage  阅读(1019)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3