0

我正在尝试访问数组中的元素,该元素位于 ArrayList 中。例如,让我们说:

ArrayList list = new ArrayList();

int[] x = new int[2];
x[0] = 2;
x[1] = 3;

list.add(x);

所以,稍后让我们说我想打印x[1],我试过这样做:

System.out.println(list.get(0)[1]); 

但这给了我:Solution.java:47:错误:不兼容的类型:对象无法转换为 int[]

我试图将数组存储在另一个数组中并访问新数组,但这给出了相同的错误消息。

我对 java 比较陌生,并且从变量并不严格的 JavaScript 迁移。我对收藏不是很熟悉,我在这里找到了这个答案:

数组内的arraylist访问

但正如您所看到的,这个解决方案对我不起作用。如果有什么我忽略或忽略的 - 我将非常感谢任何建议。谢谢你。

编辑:这个问题不是天气或不我应该使用原始数据类型 - 尽管我会确保在未来更多地审查这个 - 正在使用原始数据类型,问题是如何访问它们。

4

2 回答 2

2

您需要声明您ArrayList的类型,在这种情况下是int[]. 如果你不这样做,这ArrayList将假定它持有Objects,因此你得到的错误。它看起来像这样:

ArrayList<int[]> list = new ArrayList<int[]>();

于 2018-10-13T00:38:40.240 回答
1

ArrayList 的 get() 方法只需要索引。所以,只需使用:

System.out.println(list.get(0));
System.out.println(list.get(1));

等希望这会有所帮助。

  /**
 * Returns the element at the specified position in this list.
 *
 * @param  index index of the element to return
 * @return the element at the specified position in this list
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public E get(int index) {
    rangeCheck(index);

    return elementData(index);
}
于 2018-10-13T00:49:24.927 回答