我可以将数组插入到数组中,然后在 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
关于评论中的困惑。
List
或 List<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/