I’ve got this code started as an assignment for class. We are to set up a class that will create an array of objects. We are supposed to have two constructors so the array can be initialized with a given size, or a default size of 100. Here is what I have so far
public class Set {
private int maxObjects;
private int sz;
public Set(int maxObjects) {
this.maxObjects = maxObjects;
this.sz = maxObjects;
Object[] a = new Object[maxObjects];
}
public Set() {
this.maxObjects = 100;
this.sz = 100;
Object[] a = new Object[100];
}
public void add(Object object) {
a[0] = Object;
}
The problem I’m coming across is that it’s not seeing a as a variable in the add() method. Also the arrays are supposed to be initialized with a set capacity, but as empty, and I’m not sure how to do that.
Your problem is that
ais declared in theSetconstructor, so it’s local to the constructor. This means that it can’t be used outside of the constructor (such as from theaddmethod).The solution is pretty simple. Declare
awith your other fields:I recommend reading up on scopes in Java (a simple Google search will produce help there).
This is done by default. For an array of any non-primitive type, the array’s elements are all initialized to
null. Here, an all-nullarray is essentially an empty array. Callingnew Object[capacity]is doing this for you.