java - 将 int 数组插入到 ArrayList

标签 java arrays arraylist

我可以将数组插入到数组中,然后在 Java 中读取它吗?像这样的东西:

ArrayList<Integer> array = new ArrayList<>();
array.add([1,4,5]);
array.add([3,7,2]);

大批:
{ [1,4,5], [3,7,2] }

并阅读如下:
print(array[0][1]); //prints 4 

谢谢。

最佳答案

你可以写 ArrayList<int[]>并传递像 .add(new int[]{...}) 这样的值.

例如,

List<int[]> list = new ArrayList<>();
list.add(new int[]{1, 2, 3});

要打印出值,您应该得到一个 int[]数组首先由 get(int index)然后通过 [index] 从这个数组中获取一个值:
System.out.print(list.get(0)[0]); // prints 1

关于评论中的困惑。
  • 这里没有原始类型。 我没写,比如ListList<Object>任何地方。
  • int[]是一个数组,因此它是一个引用类型,可以用作泛型参数。
  • int是一个不能与泛型一起工作/使用的原语。考虑它的包装类 - Integer .
  • 我用的是钻石<>以上。为什么?防止“样板代码”。

  • In Java SE 7 and later, you can replace the type arguments required to invoke the constructor of a generic class with an empty set of type arguments (<>) as long as the compiler can determine, or infer, the type arguments from the context. This pair of angle brackets, <>, is informally called the diamond.
    List<int[]> list = new ArrayList<>();
    List<int[]> list = new ArrayList<int[]>(); is equivalent to the previous

    关于java - 将 int 数组插入到 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38130552/

    相关文章:

    c# - 将图像存储在 arrayList 中

    java - 这两种基于字符串的算法的复杂度是多少?

    java - 面试编程问题?(长位表示)?

    未找到 JavaScript 方法

    php - 如何检查 PHP 数组是否设置了任何值?

    java - 如何将字符串矩阵格式化为 x 行和 y 列

    android - 动态加载 Assets 文件夹中的所有图像

    java - 容器 'Maven Dependencies' 引用了不存在的库 - STS

    java - 扫描仪中的时间

    java - 如何使这个输出向后