gpt4 book ai didi

java - 尝试在 Java 中将数组添加到 ArrayList 时出错

转载 作者:行者123 更新时间:2023-11-30 02:14:15 25 4
gpt4 key购买 nike

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

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 语法:

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

关于java - 尝试在 Java 中将数组添加到 ArrayList 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49091964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com