大家好,又见面了,我是你们的朋友全栈君。
本文提供了几种Java中常用的数组转List的方法
// Array 转 List
String[] arr = {
"a", "b", "c"};
List<String> list = Arrays.asList(arr);
System.out.println(JSONObject.toJSONString(list));
输出结果:
["a","b","c"]
使用该方法有两个问题:
1. 使用Arrays.asList生成的list是定长的,无法增加或删除元素,调用add或remove方法会抛出UnsupportedOperationException异常
list.add("dd"); // list 添加元素
// list.remove(0); // list 删除元素
输出结果:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at com.xhm.test.java.collection.ArrayToList.main(ArrayToList.java:19)
2. 修改原数组中的元素值,List中对应的元素值也会改变
arr[2] = "ccc";
System.out.println(JSONObject.toJSONString(list));
输出结果:
["a","b","ccc"]
// Array 转 List
String[] arr1 = {
"a", "b", "c"};
List<String> list1 = new ArrayList<String>();
Collections.addAll(list1, arr1);
System.out.println(JSONObject.toJSONString(list1));
list1.add("d"); // list 添加元素
System.out.println(JSONObject.toJSONString(list1));
list1.remove(0); // list 删除元素
System.out.println(JSONObject.toJSONString(list1));
输出结果:
["a","b","c"]
["a","b","c","d"]
["b","c","d"]
// Array 转 List
String[] arr2 = {
"a", "b", "c"};
List<String> list2 = Arrays.stream(arr2).collect(Collectors.toList());
System.out.println(JSONObject.toJSONString(list2));
list2.add("e"); // list 添加元素
System.out.println(JSONObject.toJSONString(list2));
list2.remove(0); // list 删除元素
System.out.println(JSONObject.toJSONString(list2));
输出结果:
["a","b","c"]
["a","b","c","e"]
["b","c","e"]
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/172247.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有