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
source to share
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];
}
}
}
source to share
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);
source to share