I am having trouble compiling my java project because the array length integer (which is a variable) is not substituting correctly in my Object array.
import java.util.Arrays;
public class ObjectList {
private int N;
private Object[] fractionList = new Object[N];
public ObjectList(int n){
this.N = n;
}
public int capacity(){
return this.N;
}
public void setN(int n){
this.N = n;
}
public String toString(){
return Arrays.toString(fractionList);
}
}
public class FractionDriver {
public static void main(String[] args){
// creates the object list, sets N to 4
ObjectList list = new ObjectList(4);
System.out.println("The Objectlist has " + list.capacity() + " lines");
// prints the array
System.out.println(list.toString());
}
}
this is what the compiler outputs:
The ObjectList has 4 lines
[]
Because of this, I cannot add any objects to my array. The compiler throws an ArrayIndexOutOfBoundsException: 0 and tells me that there are no elements in the array.
If I choose to replace N in the object array instance variable, like so:
private Object[] fractionList = new Object[4];
The compiler is happy and sets the array length to 4.
What am I doing wrong?