Java Array Array of Arrays?

Rum*_*ser 44 java arrays arraylist multidimensional-array

我想创建一个没有固定大小的mutli维数组.

我需要能够添加String[2]它的项目.

我试过看:

private ArrayList<String[]> action = new ArrayList<String[2]>();
Run Code Online (Sandbox Code Playgroud)

但这不起作用.有没有人有任何其他想法?

Pét*_*rök 73

应该

private ArrayList<String[]> action = new ArrayList<String[]>();
action.add(new String[2]);
...
Run Code Online (Sandbox Code Playgroud)

您不能在generic参数中指定数组的大小,只能稍后将特定大小的数组添加到列表中.这也意味着编译器无法保证所有子阵列的大小相同,必须由您确保.

更好的解决方案可能是将其封装在一个类中,您可以在其中确保数组的统一大小作为类型不变量.


dan*_*iel 12

BTW.你应该更喜欢对接口进行编码.

private ArrayList<String[]> action = new ArrayList<String[]>();
Run Code Online (Sandbox Code Playgroud)

应该

private List<String[]> action = new ArrayList<String[]>();
Run Code Online (Sandbox Code Playgroud)

  • @athena:在Erich Gamma访谈中查看第一个问题及其答案:http://goo.gl/fz9G (3认同)
  • +1同意.此外,它通常应该被宣布为最终的.重新绑定容器变量的用例非常少. (2认同)

mis*_*tor 5

由于您的字符串数组的大小在编译时是固定的,您最好使用一个结构(如Pair)来强制要求恰好两个字段,从而避免使用数组方法可能出现的运行时错误。

代码:

由于 Java 不提供Pair类,因此您需要定义自己的类。

class Pair<A, B> {
  public final A first;
  public final B second;

  public Pair(final A first, final B second) {
    this.first = first;
    this.second = second;
  }

  //
  // Override 'equals', 'hashcode' and 'toString'
  //
}
Run Code Online (Sandbox Code Playgroud)

然后将其用作:

List<Pair<String, String>> action = new ArrayList<Pair<String, String>>();
Run Code Online (Sandbox Code Playgroud)

[ 我使用这里List是因为它被认为是对接口编程的好习惯。]