【问题标题】:Indexing a primitive array inside an ArrayList - Java [duplicate]在 ArrayList 中索引原始数组 - Java [重复]
【发布时间】:2018-10-13 00:33:32
【问题描述】:

我正在尝试访问数组中的元素,该元素位于 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 迁移过来。我对收藏不是很熟悉,我在这里找到了这个答案:

Array inside arraylist access

但如您所见,此解决方案不适用于我。如果有什么我忽略或忽略的 - 我将非常感谢任何建议。谢谢。

编辑:这个问题与天气无关,我是否应该使用原始数据类型 - 尽管我会确保在未来对此进行更多审查 - 正在使用原始数据类型,问题是如何访问它们。

【问题讨论】:

  • 不要使用原始类型。 ArrayList<int[]> list = new ArrayList<>();
  • @GBlodgett new ArrayList<>(); ;)

标签: java arrays arraylist collections


【解决方案1】:

您需要声明ArrayList 的类型,在本例中为int[]。如果你不这样做,这个ArrayList 将假定它拥有Objects,因此你得到的错误。它看起来像这样:

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

【讨论】:

  • 这太完美了,非常感谢!我需要更加熟悉泛型和类型声明。我也很欣赏快速响应和理解这个问题。我会确保查看 GBlodgett 发布的内容,但我向您保证我的问题不同。
  • 作为记录,在 Java 10 中键入 List<int[]> list = new ArrayList<>();var list = new ArrayList<int[]>(); 会更快。
【解决方案2】:

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);
}

【讨论】:

  • 返回数组,但不返回数组的索引。目标是访问数组的特定索引。不过,我很感谢您的回复。
  • 另外,我尝试将数组存储在另一个数组中,然后访问那个数组。所以,int[] f = list.get(0),这也抛出了同样的错误。
  • 对了,我看到另一个答案回去又看了一遍问题,看到了我的错误。很高兴你得到了你需要的东西。
猜你喜欢
  • 2012-08-22
  • 2016-09-22
  • 2012-02-02
  • 1970-01-01
  • 2013-01-29
  • 2011-07-18
  • 2011-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多