那麼我有一個程序可以處理由數組表示的一組圓圈。默認情況下,它的大小爲10,但如果添加了10個以上的項目,它將數組擴展10個空格。我尋找一個解決方案來降低的情況下,該組的長度在它的項數滴吹10.總是收到一個我得到一個我不知道的異常
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)
這是源:
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];
}
}
}
你的主要在哪裏? – SMA 2015-02-23 08:38:13