How many dimensions are in an array without a value

I am a bit lost (still working with Ron Jeffreys 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 empty array by setting myModel = new String[0]

. When I call myModel.myMethod()

, I get an index error. Looking at the debugger, I can see that it myModel.lines

has zero dimensions and zero length. Should it be in size and length 1? The value provided is lines[0]

equal null

, but the array itself shouldn't be, should it?

Any thoughts are greatly appreciated.

Randy

0


source to share


5 answers


I think your example probably doesn't match your actual code based on your description. I think the problem is that arrays are zero level based and hence the array is initialized like:

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 pointed out, you also need to make sure that the array itself is not null before attempting to reference it.

My 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];
        }
    }
}

      

+1


source


Strings

will be empty, so line.length will throw an exception.



I suppose your other class initializing "Model" will not help as the Line itself is private. In fact, anything you do with a model is probably illegal in at least 30 states.

+1


source


Strings

initialize before null

, check for null, or initialize it like this:

private String[] lines = new String[0];

      

+1


source


You cannot initialize a model instance by setting it equal to a String array. I'm really surprised the compiler will let you even try.

If you really want the model to be initialized with an external array, you must make a Constructor for the Model class that takes an array as an argument. Then, in the body of your constructor, set the string value to that value.

Example:

public class Model {
    private String []lines;

    public Model(String [] inLines)
       {
       lines = inLines;
       }
}

      

Using:

myStringArray = new String[0];
myModel = new Model(myStringArray);

      

+1


source


Take a look at my answer here - I think this will give you the background you are looking for on the differences between array initialization in Java and C / C ++.

0


source







All Articles