Alpha
Alpha

Reputation: 14026

How to store data with varying number of rows in Java?

I've to pass something like following to a method:

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

In above case, I know that number of columns are fixed ie. 3 but I don't know number of rows. Sometime rows can be 2 or rows can be 10. Number of rows vary.

I want to store such object. I tried with:

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

but this is not supported. Could you please provide some another solution for the problem?

Upvotes: 0

Views: 57

Answers (3)

Laurent Simon
Laurent Simon

Reputation: 582

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.

Upvotes: 0

ergonaut
ergonaut

Reputation: 7057

Assuming you want to avoid using collections and stick with String, you can simply make the assumption that there are three strings, and just assign it to an array of arrays as such.

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

Then when you reference it, don't go past the third element.

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

For simple examples this is okay, but when you get into more advance coding, you would ideally be looking at the List type.

Upvotes: 0

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

Java doesn't support unknown sized arrays and that's why statements like new String[][3] don't compile.

The List interface can actually serve similar purpose, so you could do:

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

Upvotes: 6

Related Questions