在Java中将数组转换为列表 [英] Converting array to list in Java

查看:55
本文介绍了在Java中将数组转换为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Java 中将数组转换为列表?

How do I convert an array to a list in Java?

我使用了 Arrays.asList() 但行为(和签名)不知何故从 Java SE 1.4.2(文档现在存档)到 8 和我在网上找到的大多数片段都使用 1.4.2 行为.

I used the Arrays.asList() but the behavior (and signature) somehow changed from Java SE 1.4.2 (docs now in archive) to 8 and most snippets I found on the web use the 1.4.2 behaviour.

例如:

int[] spam = new int[] { 1, 2, 3 };
Arrays.asList(spam)

  • 在 1.4.2 上返回一个包含元素 1、2、3 的列表
  • 在 1.5.0+ 上返回一个包含数组 spam 的列表
  • 在许多情况下,它应该很容易被发现,但有时它可能会被忽视:

    In many cases it should be easy to detect, but sometimes it can slip unnoticed:

    Assert.assertTrue(Arrays.asList(spam).indexOf(4) == -1);
    

    推荐答案

    在您的示例中,这是因为您不能拥有原始类型的 List.换句话说,List<int> 是不可能的.

    In your example, it is because you can't have a List of a primitive type. In other words, List<int> is not possible.

    但是,您可以使用 Integer 类,它包装了 int 原语.将您的数组转换为 ListArrays.asList 实用方法.

    You can, however, have a List<Integer> using the Integer class that wraps the int primitive. Convert your array to a List with the Arrays.asList utility method.

    Integer[] spam = new Integer[] { 1, 2, 3 };
    List<Integer> list = Arrays.asList(spam);
    

    查看此在 IdeOne.com 上运行的代码.

    这篇关于在Java中将数组转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆