我可以在java ???
中创建这样的数组Array
([0]
array
[items1] = "one"
[items2] = "two"
[items3] = "three")
([1]
array
[items1] = "one###"
[items2] = "two###"
[items3] = "three#")
Thanx求助
答案 0 :(得分:3)
是的,您可以通过创建数组数组来完成此操作。例如:
String[][] twoDimensionalPrimitiveArray = {
{"one", "two", "three"},
{"one###", "two###", "three###"}
};
您也可以使用集合类型执行此操作:
List<List<String>> listOfLists = new ArrayList<>();
listOfLists.add(createList("one", "two", "three"));
listOfLists.add(createList("one###", "two###", "three###"));
// ...
private static List<String> createList(String... values) {
List<String> result = new ArrayList<>();
for (String value : values) {
result.add(value);
}
return result;
}
修改的
@immibis在评论中正确地指出createList()
可以更简单地写成new ArrayList(Arrays.asList(values))
。
答案 1 :(得分:2)
是的,您可以定义一个数组数组:
String[][] arrayOfArrays = new String[2][]; // declare and initialize array of arrays
arrayOfArrays[0] = new String[3]; // initialize first array
arrayOfArrays[1] = new String[3]; // initialize second array
// fill arrays
arrayOfArrays[0][0] = "one";
arrayOfArrays[0][1] = "two";
arrayOfArrays[0][2] = "three";
arrayOfArrays[1][0] = "one###";
arrayOfArrays[1][1] = "two###";
arrayOfArrays[1][2] = "three#";
并测试它(打印值):
for (String[] array : arrayOfArrays) {
for (String s : array) {
System.out.print(s);
}
System.out.println();
}
答案 2 :(得分:1)
对于Java中的二维数组,您可以按如下方式创建它们:
// Example 1:
String array[][] = {"one", "two", "three"},{"one###", "two###", "three###"}};
或者你可以定义数组,然后填写每个元素,但这更乏味,但这可能更适合你的需要。
// Example 2:
String array[][] = new String[2][3];
array[0][0] = "one";
array[0][1] = "two";
array[0][2] = "three";
array[1][0] = "one###";
array[1][1] = "two###";
array[1][2] = "three#";
答案 3 :(得分:0)
String[] twoDArray[] = {{"one", "two", "three"}, {"one###", "two###", "three###"}};