Java 你如何创建一个整数 ArrayList?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4075093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:19:19  来源:igfitidea点击:

How do you create an integer ArrayList?

javagenericsarraylist

提问by Tomek

I am trying to create an array of Arraylists in Java. I have declared it in the following way:

我正在尝试用 Java 创建一个数组列表。我已通过以下方式声明它:

ArrayList[][][] arrayQ = new ArrayList[90][13][18];

for (int i = 0; i < 90; i++) {
  for (int j = 0; j < 13; j++) {
    for (int k = 0; k < 18; k++) {
      arrayQ[i][j][k] = new ArrayList<int>();
    }  
  } 
}

However, adding the <int>inside the while loop throws an error (the IDE I'm using unfortunately doesn't give me a very good error message).

但是,<int>在 while 循环中添加内部会引发错误(不幸的是,我正在使用的 IDE 并没有给我一个很好的错误消息)。

What's the proper way to create an integer ArrayList?

创建整数 ArrayList 的正确方法是什么?

回答by joschi

Java Collections can only hold objects. intis a primitive data type and cannot be held in an ArrayListfor example. You need to use Integerinstead.

Java 集合只能保存对象。int是一种原始数据类型,不能保存在ArrayList例如。您需要改用Integer

回答by Andy White

It looks like you're mixing the non-generic and generic ArrayLists. Your 3D array of ArrayListuses the non-generic, but you are trying to assign a generic ArrayList<int>. Try switching one of these to match the other.

看起来您正在混合 non-generic 和 generic ArrayLists。您的 3D 数组ArrayList使用非泛型,但您正在尝试分配泛型ArrayList<int>. 尝试切换其中一个以匹配另一个。

回答by Andy Dvorak

joschi and Cristian are correct. Change new ArrayList<int>()to new ArrayList<Integer>()and you should be fine.

joschi 和 Cristian 是正确的。更改new ArrayList<int>()new ArrayList<Integer>(),你应该罚款。

If at all possible, I would recommend using Eclipseas your IDE. It provides (usually) very specific, detailed, and generally helpful error messages to help you debug your code.

如果可能的话,我建议使用Eclipse作为您的 IDE。它提供(通常)非常具体、详细且通常有用的错误消息,以帮助您调试代码。

回答by EboMike

The problem is that an ArrayListrequires Objects- you cannot use primitive types.

问题是ArrayList需要Objects- 您不能使用原始类型。

You'll need to write arrayQ[i][j][k] = new ArrayList<Integer>();.

你需要写arrayQ[i][j][k] = new ArrayList<Integer>();.

回答by robertmoggach

Here's a complete example:

这是一个完整的例子:

ArrayList<Integer>[] foo = new ArrayList[3];

foo[0] = new ArrayList<Integer>();
foo[1] = new ArrayList<Integer>();
foo[2] = new ArrayList<Integer>();

foo[0].add(123);
foo[0].add(23);
foo[1].add(163);
foo[1].add(23789);
foo[2].add(3);
foo[2].add(2);

for (ArrayList<Integer> mylist: foo) {
  for (int bar : mylist) {
    println(bar);
  }
}