Reputation: 1091
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.
Upvotes: 1
Views: 4816
Reputation: 729
You should define a
the same place you defined maxObjects and sz.
private Object[] a;
Then place this in your constructors:
a = new Object[maxObjects];
Read about the scope of variables.
Upvotes: 4
Reputation: 425428
Couple of things:
a
should be a fieldTry this:
public class Set {
private int maxObjects;
private int sz;
private Object[] a;
public Set(int maxObjects) {
this.maxObjects = maxObjects;
this.sz = maxObjects;
a = new Object[maxObjects];
}
public Set() {
this(100); // fyi, this is the syntax for calling another constuctor
}
public void add(Object object) {
a[0] = object;
}
}
Upvotes: 1
Reputation: 17329
It's not seeing
a
as a variable in theadd()
method
Your problem is that a
is declared in the Set
constructor, so it's local to the constructor. This means that it can't be used outside of the constructor (such as from the add
method).
The solution is pretty simple. Declare a
with your other fields:
public class Set {
private int maxObjects;
private int sz;
private Object[] a;
public Set(int maxObjects) {
this.maxObjects = maxObjects;
this.sz = maxObjects;
this.a = new Object[maxObjects];
}
public Set() {
this.maxObjects = 100;
this.sz = 100;
this.a = new Object[100];
}
public void add(Object object) {
a[0] = object;
}
}
I recommend reading up on scopes in Java (a simple Google search will produce help there).
Also the arrays are supposed to be initialized with a set capacity, but as empty.
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-null
array is essentially an empty array. Calling new Object[capacity]
is doing this for you.
Upvotes: 1
Reputation: 12396
You are very close to having this correct. The problem you have is related to the scope of variables. Examine closer the scope of variable a.
Also you have a typo in your add method.
a[0] = Object
should be
a[0] = object
(with a lower case o)
Upvotes: 2