我创建了一个名为 current_map
的多维数组。
我正在尝试访问 current_map
:
current_map[0][1]
但是我收到错误:
error: array required, but String found
这是我的代码,供您欣赏
import java.util.*;
import java.util.Map.Entry;
import java.util.ArrayList;
public class TestApp {
private ArrayList<String[]> current_map = new ArrayList<String[]>();
public TestApp() {
current_map.add(new String[] { "0","0","0" });
current_map.add(new String[] { "0","Q","0" });
current_map.add(new String[] { "0","0","0" });
}
public String getValue(int X,int Y){
String[] obj_map = current_map.toArray(new String[current_map.size()]);
return obj_map[X][Y]; // for example, getValue(2,2), should give "Q"
}
}
我怎样才能阻止这个问题?
最佳答案
你可以这样做:
import java.util.*;
import java.util.Map.Entry;
import java.util.ArrayList;
public class TestApp {
private ArrayList<String[]> current_map = new ArrayList<String[]>();
public TestApp() {
current_map.add(new String[] { "0","0","0" });
current_map.add(new String[] { "0","Q","0" });
current_map.add(new String[] { "0","0","0" });
}
public String getValue(int X,int Y){
return current_map.get(Y)[X]; // for example, getValue(2,2), should give "Q"
}
public static void main(String[] args) {
TestApp ta = new TestApp();
System.out.println(ta.getValue(1, 1));
}
}
请注意,在 Java 中,数组索引是从 0 开始的,因此第 2 行、第 2 列用 (1, 1) 而不是 (2, 2) 表示。
希望这对您有所帮助。
关于java - ArrayList 中的数组问题,Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9882740/