[英]Java 2D Int Arraylist
I dont quite understand what is the problem with the second declaration. 我不太明白第二个声明有什么问题。
// Compiles fine
ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
// error (Unexpected type, expected -reference ,found :int)
ArrayList<ArrayList<int>> intarray = new ArrayList<ArrayList<int>>();
The way generics work is simple. 泛型的工作方式很简单。 The header of
List
looks a little like this: List
的标题看起来像这样:
public interface List<T>
Where T
is some Object
. 其中
T
是一些Object
。 However, int
is not a subclass of Object
. 但是,
int
不是Object
的子类。 It is a primitive. 这是原始的。 So how do we get around this?
那么我们如何解决这个问题? We use
Integer
. 我们使用
Integer
。 Integer
is the wrapper class for int
. Integer
是int
的包装器类。 This allows us to use int
values in a List
, because when we add them, they get auto boxed into Integer
. 这使我们可以在
List
使用int
值,因为添加它们时,它们会自动装箱到Integer
。
Primitive types are actually scheduled for deprecation in Java 10. Taken from Wikipedia: 实际上,已计划在Java 10中弃用基本类型。取自Wikipedia:
There is speculation of removing primitive data types, as well as moving towards 64-bit addressable arrays to support large data sets somewhere around 2018.
人们猜测将删除原始数据类型,并转向64位可寻址阵列以支持大约2018年左右的大型数据集。
Just a Note on your Code 只是关于您的代码的注释
In Java, the convention is to have the declaration using the most generic type and the definition using the most specific concrete class . 在Java中,约定是使用最通用的类型进行声明,使用最具体的具体类进行定义。 For example:
例如:
List myList;
// List is the interface type. This is as generic as we can go realistically.
myList = new ArrayList();
// This is a specific, concrete type.
This means that if you want to use another type of List
, you won't need to change much of your code. 这意味着,如果要使用其他类型的
List
,则无需更改太多代码。 You can just swap out the implementation. 您可以换掉实现。
Extra Reading 额外阅读
ArrayList
is an implementation of List<T>
, your problem is that you are trying to create an arraylist of int, its impossible since int
is not an object. ArrayList
是List<T>
的实现,您的问题是您试图创建一个int的arraylist,这是不可能的,因为int
不是对象。 using Integer
will solve your problem. 使用
Integer
将解决您的问题。
ArrayList<ArrayList<Integer>> intarray = new ArrayList<ArrayList<Integer>>();
You can only make List of Objects. 您只能创建对象列表。 int is a primitive type.
int是原始类型。
Try use: 尝试使用:
ArrayList<ArrayList<Integer>> intarray = new ArrayList<ArrayList<Integer>>();
您必须创建一个ArrayList<Integer>
而不是ArrayList<int>
一个类(在您的情况下为Arraylist
)可以是CLASS的类型( Integer
)
ArrayList does not except primitive types as an argument. ArrayList不会将原始类型作为参数。 It only accepts Object types you should use:
它仅接受您应该使用的对象类型:
ArrayList<ArrayList<Integer>> intArray = new ArrayList<ArrayList<Integer>>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.