问题描述:对于给定的如下数组,如何转换成List集合?

String[] array = {"a","b","c"};

参考stackoverflow总结如下几种写法:

1.使用原生方式,拆分数组,添加到List

List<String> resultList = new ArrayList<>(array.length);
for (String s : array) {
    resultList.add(s);
}

2.使用Arrays.asList()

List<String> resultList= new ArrayList<>(Arrays.asList(array));
  • 注意:调用Arrays.asList()时,其返回值类型是ArrayList,但此ArrayListArray的内部类,调用add()时,会报错:java.lang.UnsupportedOperationException,并且结果会因为array的某个值的改变而改变,故需要再次构造一个新的ArrayList
  • 注意:Arrays.asList(char[])将转为List<char[]>,因为要求参数为T变长数组,char不是T,同理int[]数组也不行,你必须要用Integer[]

3.使用Collections.addAll()

List<String> resultList = new ArrayList<>(array.length);
Collections.addAll(resultList,array);

4.使用List.of()

  • 此方法为 Java9新增方法,定义在List接口内,并且为静态方法,故可以由类名直接调用。
List<String> resultList = List.of(array);

相关文章:

  • 2021-12-26
  • 2021-11-13
  • 2021-11-13
  • 2021-12-28
  • 2021-11-20
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-28
  • 2021-12-18
  • 2022-12-23
  • 2022-12-23
  • 2021-11-24
相关资源
相似解决方案