尝试将数组添加到Java中的ArrayList时出错[重复]

问题描述 投票:1回答:2

这个问题在这里已有答案:

所以我试图将二维数组添加到数组列表中,如下所示:

public class game{

        static ArrayList<Object> edges = new ArrayList<Object>();

        static void setEdges(){
            for(int i=0;i<8;i++){
                for(int j=0;j<8;j++){
                    edges.add( {9*i+j,9*i+j+1} );
                    edges.add( {9*i+j , 9*i+j+9} );
                }
            }
        }
   }

但它不起作用。看起来有用的是:

public class game{

        static ArrayList<Object> edges = new ArrayList<Object>();

        static void setEdges(){
            for(int i=0;i<8;i++){
                for(int j=0;j<8;j++){
                    int[] edge = {9*i+j,9*i+j+1};
                    int [] edge2 = {9*i+j , 9*i+j+9};
                    edges.add( edge2 );
                    edges.add( edge );
                }
            }
        }
   }

我无法理解为什么最简单的方法不起作用而另一方法起作用。

java multidimensional-array
2个回答
3
投票

这是因为您编写的内容不是有效的Java语法:

edges.add( {9*i+j,9*i+j+1} );
edges.add( {9*i+j , 9*i+j+9} );

您需要明确指定要添加数组:

edges.add(new int[] {9 * i + j, 9 * i + j + 1});
edges.add(new int[] {9 * i + j, 9 * i + j + 9});

-1
投票

我认为这是正常的,因为你试图将一个Integer添加到一个强大的对象(边缘)数组中而不进行强制转换。所以如果你想要那个工作用Integer替换Object :)

© www.soinside.com 2019 - 2024. All rights reserved.