【问题标题】:Error trying to add Arrays to an ArrayList in Java [duplicate]尝试将数组添加到 Java 中的 ArrayList 时出错 [重复]
【发布时间】:2018-08-12 00:23:44
【问题描述】:

所以我试图将二维数组添加到这样的数组列表中:

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

我不明白为什么最简单的方法不起作用,而另一种方法却起作用。

【问题讨论】:

  • 你为什么用Object而不是int[]
  • 因为我不知道你可以在 里面写什么类型。

标签: java multidimensional-array


【解决方案1】:

我认为这很正常,因为您尝试将 Integer 添加到对象(边缘)数组的强度中而没有强制转换。因此,如果您希望该工作将 Object 替换为 Integer :)

【讨论】:

    【解决方案2】:

    这是因为你写的不是有效的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});
    

    【讨论】:

      猜你喜欢
      • 2018-05-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 2022-01-19
      • 2014-04-21
      • 2017-03-11
      • 2023-03-28
      相关资源
      最近更新 更多