简体   繁体   English

我可以在Java中初始化2D数组的数组/ arraylist <int>吗?

[英]Can I initialize a array/arraylist<int> of 2D array in Java?

Can I initialize ArrayList of 2D array, is this a thing? 我可以初始化2D数组的ArrayList,这是一个什么东西?

So when I try to initialize this, below is my code 所以当我尝试初始化时,下面是我的代码

ArrayList<int>[][] suffle = new ArrayList<int>[row][col]; 

I get an error like this: 我收到这样的错误:

Error: Syntax error, insert "Dimensions" to complete ReferenceType 错误:语法错误,插入“Dimensions”以完成ReferenceType

How can I fix this? 我怎样才能解决这个问题?

It is a thing, but you have to use an object, not a primitive. 这是一件事,但你必须使用一个对象,而不是一个原始对象。 This applies to all generic types. 这适用于所有通用类型。

ArrayList<Integer>[][] suffle = new ArrayList[row][col];

You're going to get some compiler warnings about the above declaration, but it is perfectly possible to do. 您将获得有关上述声明的编译器警告,但完全可以这样做。

Depending on what it is you're doing, it might be better to use a list of lists, which will ensure type safety as oppose to the unchecked warning you'd get from the above... 根据您正在做的事情,最好使用列表列表,这将确保类型安全性与您从上面得到的未经检查的警告相反...

List<List<Integer>> suffle = new ArrayList<>();

...or a standard two-dimensional array: ......或标准的二维数组:

int[][] suffle = new int[row][col];

You can also stick entirely with primitives, ie 你也可以完全坚持原语,即

 int[][] i = new int[row][col]; 

Or mix and match a list of int[] 或者混合并匹配int []列表

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

And almost an array of lists: 几乎是一系列的清单:

/* writing new ArrayList<Integer>[1], which is what 
you'd want to do, is not allowed for array creation.*/
ArrayList<Integer>[] a = new ArrayList[1]; 

Yes, you can make a 2-dimensional array of Object types (in this case ArrayList). 是的,您可以创建一个Object类型的二维数组(在本例中为ArrayList)。

But you need to write it as: 但你需要把它写成:

ArrayList<Integer>[][] suffle = new ArrayList[row][col];

Also make sure you initialize row and col as integer values, before you initialize the array list. 在初始化数组列表之前,还要确保将row和col初始化为整数值。

The individual elements of suffle will be declared as ArrayList types, but not initialized. suffle的各个元素将被声明为ArrayList类型,但不会被初始化。 You'll need to individually initialize them. 您需要单独初始化它们。

Wherever you need to use generic types within diamond brackets, you should not use primitive types such as int, double etc. Rather, respective wrapper types such as Integer and Double etc should be used. 无论何时需要在菱形括号中使用泛型类型,都不应使用原始类型,如int,double等。应使用相应的包装类型,如Integer和Double等。

After I saw this question being asked in many forums, I have explained this with examples on my blog as well - http://www.javabrahman.com/corejava/how-to-resolve-syntax-error-insert-dimensions-to-complete-referencetype/ 我在许多论坛上看到这个问题后,我已经在我的博客上用例子解释了这个问题 - http://www.javabrahman.com/corejava/how-to-resolve-syntax-error-insert-dimensions-to -完整,引用类型/

(Note/Disclosure - the above link is from a blog owned by me) (注意/披露 - 以上链接来自我拥有的博客)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM