EoRaptor013 EoRaptor013 - 5 days ago 7
Java Question

How many dimensions in an array with no value

I'm a little lost (still working with Ron Jeffries's book). Here's a simple class:

public class Model{
private String[] lines;

public void myMethod(){
String[] newLines = new String[lines.length + 2];
for (i = 0, i <= lines.length, i++) {
newLines[i] = lines[i];
}
}
}


I have another class that initializes
Model
, and an empty array, by setting
myModel = new String[0]
. When I invoke
myModel.myMethod()
, I get a subscript out of range error. Looking at the debugger, what I see is that
myModel.lines
has zero dimensions and zero length. Shouldn't it have a dimension and length of 1? Granted the value of
lines[0]
is
null
, but the array itself shouldn't be, should it?

Any thoughts truly appreciated.

Randy

Answer

I think your example is probably not the same as your actual code based on your description. I think the problem is that arrays are zero-based and thus an array initialized as:

string[] lines = new string[0];

has no elements.

You need to change your loop so that you check that the index is strictly less than the length of the array. As others have indicated you also need to make sure that the array itself is not null before trying to reference it.

My take on your code:

public class Model{
    private String[] lines = new string[0];

    public Model( string[] lines ) {
        this.lines = lines;
    }

    public void myMethod(){
        int len = 2;
        if (lines != null) {
            len = len + lines.length;
        }
        String[] newLines = new String[len];
        for (i = 0, i < lines.length, i++) {
            newLines[i] = lines[i];
        }
    }
}
Comments