前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >数组转为list java_思考与实践并行的俗语

数组转为list java_思考与实践并行的俗语

作者头像
全栈程序员站长
发布2022-09-23 11:26:00
2620
发布2022-09-23 11:26:00
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君

不曾想到,“Java数组转List”竟然有这么多的学问,震撼之余夹带些许不堪。关于“Java数组转List”其实是非常基础的知识,况且有很多人在博客中均有所讨论,难免让我觉得写这样的讨论文章显得多少没有必要!转念想到“不积硅步,无以成千里”,于是强迫自己再次对该问题做一些深层次的实践。

一、Create ArrayList from array

Create ArrayList from array在stackoverflow上引发的讨论之热烈程度多少让我感到吃惊:

  1. new ArrayList(Arrays.asList(array))
  2. List list = Arrays.asList(array);
  3. Use Guava ——Lists.newArrayList(aStringArray);
  4. Collections.addAll(arraylist, array);
  5. for(Element e : array) —— list.add(e);

从里面可以提取出以上五种的方案,关于Guava的,由于我对此不甚了解,所以暂时放过,那么剩余四种情况,我们就详细来做实践。

①、new ArrayList(Arrays.asList(array))

其实我觉得第一种方案,挺简洁好使的。

代码语言:javascript
复制
String[] array1 = { new String("1"), new String("2"), new String("3") };

arrayList = new ArrayList<String>(Arrays.asList(array1));

for (String s : arrayList) {
    System.out.print(s + "、");
}

try {
    arrayList.add("111");

    for (String s : arrayList) {
        System.out.print(s + "、");
    }
} catch (Exception e) {
    System.out.print(e);
}

try {
    array[1] = "qw";

    for (String s : arrayList) {
        System.out.print(s + "、");
    }
} catch (Exception e) {
    System.out.print(e);
}

System.out.println();
System.out.println("----------new ArrayList<String>(Arrays.asList(array1))---------------");

输出内容如下:

1、2、3、1、2、3、111、1、2、3、111、 ———-new ArrayList(Arrays.asList(array1))—————

但是,看完stackoverflow上的讨论,觉得这种方案确实有最大的弊端!

you may create and fill two lists !

好吧,这个过程会产生两个list,真让人操碎了心啊!不过请注意,该种方法与第二种方法之间多了一个“new ArrayList”,那么为什么要再new一次呢?请看第二种方法的介绍!

②、List list = Arrays.asList(array)

从java的API中我们可以看出

asList public static List asList(T… a)返回一个受指定数组支持的固定大小的列表。(对返回列表的更改会“直接写”到数组。)此方法同 Collection.toArray() 一起,充当了基于数组的 API 与基于 collection 的 API 之间的桥梁。返回的列表是可序列化的,并且实现了 RandomAccess。 此方法还提供了一个创建固定长度的列表的便捷方法,该列表被初始化为包含多个元素: List<String> stooges = Arrays.asList("Larry", "Moe", "Curly"); 参数: a – 支持列表的数组。 返回: 指定数组的列表视图。

此方法会有两个弊端:

  1. list长度固定,也就是说无法进行add元素。
  2. 对返回列表的更改会“直接写”到数组。

我们接着看例子:

代码语言:javascript
复制
String[] array = { new String("1"), new String("2"), new String("3") };

List<String> arrayList = Arrays.asList(array);

for (String s : arrayList) {
    System.out.print(s + "、");
}

try {
    arrayList.add("111");

    for (String s : arrayList) {
        System.out.print(s + "、");
    }
} catch (Exception e) {
    System.out.print(e);
}

try {
    arrayList.set(1, "qw");

    for (String s : array) {
        System.out.print(s + "、");
    }
} catch (Exception e) {
    System.out.print(e);
}

System.out.println();
System.out.println("----------Arrays.asList---------------");

输出结果如下:

1、2、3、java.lang.UnsupportedOperationException1、qw、3、 ———-Arrays.asList—————

从结果中可以证明:

This will work fine. But some caveats:

  1. The list returned from asList has fixed size. So, if you want to be able to add or remove elements from the returned list in your code, you’ll need to wrap it in a new ArrayList. Otherwise you’ll get an UnsupportedOperationException.
  2. The list returned from asList() is backed by the original array. If you modify the original array, the list will be modified as well. This may be surprising.

所以该种“数组转换为List”的做法局限很多,限制了转换后List的使用!

那么再回到第一种方法“new ArrayList(Arrays.asList(array))”上,使用new ArrayList显然规避了以上两种限制,但同时创建了两个list,所以以上两种方法虽然在代码量上足够简洁,但弊端同样很多,也就是说这两种方法多少有点“后遗症”。

④、Collections.addAll(arraylist, array);

跳过Guava,我们来看“Collections.addAll(arraylist, array)”。

代码语言:javascript
复制
String[] array2 = { new String("1"), new String("2"), new String("3") };

arrayList = new ArrayList<String>();
Collections.addAll(arrayList, array2);

for (String s : arrayList) {
    System.out.print(s + "、");
}

try {
    arrayList.add("111");

    for (String s : arrayList) {
        System.out.print(s + "、");
    }
} catch (Exception e) {
    System.out.print(e);
}

try {
    array[1] = "qw";

    for (String s : arrayList) {
        System.out.print(s + "、");
    }
} catch (Exception e) {
    System.out.print(e);
}

System.out.println();
System.out.println("-------------Collections.addAll(arrayList, array2)------------");

对于第四种方法,我觉得还不错,代码也足够的简洁,且没有多余的“后遗症”,所以推荐这种做法!

另外,通过api可以看到如下解释:

public static boolean addAll(Collection< ? super T> c,T… elements) 将所有指定元素添加到指定 collection 中。可以分别指定要添加的元素,或者将它们指定为一个数组。此便捷方法的行为与 c.addAll(Arrays.asList(elements)) 的行为是相同的,但在大多数实现下,此方法运行起来可能要快得多。 在分别指定元素时,此方法提供了将少数元素添加到现有 collection 中的一个便捷方式: Collections.addAll(flavors, “Peaches ‘n Plutonium”, “Rocky Racoon”);

该方式对应还有另外一种写法

代码语言:javascript
复制
String[] array3 = { new String("1"), new String("2"), new String("3") };

ArrayList<String> arrayList3 = new ArrayList<String>();
arrayList3.addAll(Arrays.asList(array3));

这种写法就不如Collections.addAll!

⑤、for(Element e : array) —— list.add(e);

其实,很多时候我们忽略了最原始的写法,也就是所谓的

代码语言:javascript
复制
arrayList3 = new ArrayList<String>();
for (String s : array3) {
    arrayList3.add(s);
}

这种写法在我看来,也足够的简洁,同样没有后遗症,并且运行速度,我想,肯定不慢!


总结完上述“Java数组转换为List”方法后,真心感觉原来基础知识也这么有深度,赶紧学起来吧!


感谢您阅读【沉默王二的博客】,如果王二的博客给您带来一丝帮助或感动,我(也就是王二)将不甚荣幸。 如果您碰巧喜欢,可以留言或者私信我,这将是我鼓捣更多优秀文章的最强动力。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/172257.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、Create ArrayList from array
    • ①、new ArrayList(Arrays.asList(array))
      • ②、List list = Arrays.asList(array)
        • ④、Collections.addAll(arraylist, array);
          • ⑤、for(Element e : array) —— list.add(e);
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档