Reputation: 2387
Well I have a program which handles a set of circles represented by an array. It's by default is of size of 10, but if more than 10 items are added, it extends the array by 10 more spaces. I looked for a solution to reduce the length of the set in case the number of items in it drops blow 10. I keep getting a
Exception in thread "main" java.lang.ArrayStoreException: oop.Circle
at oop.ObjectSet.reduce(ObjectSet.java:94)
at oop.ObjectSet.removeObject(ObjectSet.java:39)
at oop.CircleSet.removeObject(CircleSet.java:17)
at oop.Test.main(Test.java:60)
This is the source:
package oop;
public class ObjectSet {
protected Object[] objectSet;
protected int size;
public ObjectSet() {
objectSet = new Object[10];
size = 0;
}
public int numberOfItems() {
return size;
}
public boolean addObject(Object object) {
if (object != null) {
if (size == 0)
objectSet[size] = object;
if (size == objectSet.length)
extend();
if (contains(object) == -1) {
objectSet[size] = object;
size++;
return true;
}
}
return false;
}
public boolean removeObject(Object object) {
if (object != null && size > 0) {
int index = contains(object);
if(size == this.objectSet.length - 10)
reduce();
for (int i = index; i < size; i++) {
objectSet[i] = objectSet[i + 1];
}
objectSet[size - 1] = null;
size--;
return true;
}
return false;
}
public int contains(Object object) {
if (object != null && size > 0) {
for (int i = 0; i < size; i++) {
if (objectSet[i].equals(object))
return i;
}
}
return -1;
}
public void printSet(){
if(size > 0){
for (int i = 0; i < size; i++) {
System.out.println();
}
}
}
private void extend() {
Object[] temp = new Object[size];
for (int i = 0; i < size; i++) {
temp[i] = this.objectSet[i];
}
this.objectSet = new Object[size + 10];
for (int i = 0; i < size; i++) {
this.objectSet[i] = temp[i];
}
}
private void reduce(){
int newSize = this.objectSet.length - 10;
Object[] temp = new Object[newSize];
for (int i = 0; i < size; i++) {
temp[i] = this.objectSet[i];
}
this.objectSet = new ObjectSet[newSize];
for (int i = 0; i < size; i++) {
this.objectSet[i] = temp[i];
}
}
}
Upvotes: 1
Views: 72
Reputation: 140534
You are trying to store Object
instances in an array of ObjectSet
. This line:
this.objectSet = new ObjectSet[newSize];
Should be
this.objectSet = new Object[newSize];
As it is in the extend method.
Note that you also need to change the subsequent loop termination condition to i < newSize
.
Upvotes: 1
Reputation: 394126
Sometimes you initialize the array as
this.objectSet = new Object[size + 10];
while other times you initialize it as
this.objectSet = new ObjectSet[newSize];
This is probably the cause of the exception.
I'm assuming you meant the latter to be :
this.objectSet = new Object[newSize];
Upvotes: 1