如何在Java中存储具有不同行数的数据?

时间:2016-04-15 13:57:02

标签: java

我将以下内容传递给方法:

{
  {"First", "John", "Male"},
  {"Second", "Michelle", "Female"},
  .
  .
  .
}

在上面的例子中,我知道列的数量是固定的,即。 3但我不知道行数。有时行可以是2行或行可以是10.行数不同。

我想存储这样的对象。我尝试过:

String[][] ar = new String[][3];

但不支持此功能。你能否为这个问题提供另一种解决方案?

3 个答案:

答案 0 :(得分:7)

Java不支持未知大小的数组,这就是new String[][3]这样的语句不能编译的原因。

List界面实际上可以起到类似的作用,所以你可以这样做:

List<String[]> listOfArrays = new ArrayList<String[]>();

答案 1 :(得分:0)

假设你想避免使用集合并坚持使用String,你可以简单地假设有三个字符串,并且只是将它分配给一个数组数组。

String [][] ar = {
                  {"First", "John", "Male"},
                  {"Second", "Michelle", "Female"},
                  {"Third", "John", "Male"},
                };

然后当你引用它时,不要超过第三个元素。

for (int i=0;i<3;i++){
    // do something with ar[0][i]
}

对于简单的例子,这是可以的,但是当你进入更高级的编码时,理想情况下你会看到List类型。

答案 2 :(得分:0)

Using unbounded lists or arrays like in @konstantin-yovkovworks or @ergonaut answers works. And, it is exactly what you asked for. But, when doing like this, the contract between the caller and the callee is very weak. It is not reliable. The called method need to check everything before using it because no usage contract is clearly defined for the compiler.

Generally, it is far better to use a clear contract. In your case, it should be something like:

public final class Row {

   public final String rank;
   public final String name;
   public final String sex;

   public Row( final String rank, final String name, final String sex ) {
       this.rank = rank;
       this.name = name;
       this.sex = sex;
   }

}

The called function API can be, for example:

public void calledMethod( Row ... rows);

or

public void calledMethod( Row[] rows);

And, it can be used like that :

calledMethod(
    new Row( "First", "John", "Male" ),
    new Row( "Second", "Michelle", "Female" ),
    ,
    ,
);

This is far more reliable and easier to understand by those who will need to read your code later.