1
我需要爲PositionalList創建一個添加方法...它使用數組來存儲數據。這裏是私有成員和構造函數:爲PositionalList添加方法
private static int DEFAULT_CAPACITY = 10;
private Object[] items;
private int listSize;
private int curPos;
private int lastItemPos;
public FSAPositionalList(){
items = new Object[DEFAULT_CAPACITY];
listSize= 0;
curPos = 0;
lastItemPos = -1;
}
僞碼的方法,我由是:
1)檢查陣列OOB。 2.)從當前位置創建臨時陣列 - >列表結尾 3.)在當前位置添加項目 4.)從curPos + 1開始重新添加來自臨時數組的項目。
這裏是我的方法,當前的代碼:
public void add(Object obj){
// Check For Out of Bounds
if(listSize+1 > DEFAULT_CAPACITY){
throw new RuntimeException("Too many items.");
}else{
//if first time then otherwise
if(listSize == 0){
System.out.println("Permission Granted");
items[curPos] = obj;
listSize++;
return;
}
System.out.println("Access");
// Create temp array from curPos --> end
Object temp[] = new Object[listSize-curPos];
//populate temp array
int counter = 0;
for(int i = curPos; i<listSize; i++){
temp[counter] = items[i];
System.out.print("Temp - " + temp[counter]);
counter++;
}
System.out.println();
// Insert obj
items[curPos] = obj;
System.out.println(" Temp Array: ");
for(int i = 0; i < temp.length; i++){
System.out.println(temp[i]);
}
// re-add temparray after obj
int c = 0;
for(int i = curPos+1; i<listSize; i ++){
System.out.println("Replacing " + i + " " + items[i] + " with " + temp[c]);
items[i] = temp[c];
c++;
}
listSize++;
}
使用測試類,如下所示:
FSAPositionalList list = new FSAPositionalList();
System.out.println("Adding 1");
list.add(1);
System.out.println(" List : " + list);
System.out.println("Adding 2");
list.add(2);
System.out.println(" List : " + list);
System.out.println("Adding 3");
list.add(3);
System.out.println(" List : " + list);
System.out.println("Adding 66");
list.next();
list.add(66);
System.out.println(" List : " + list);
System.out.println(list);
我得到這樣的輸出:
Adding 1
Permission Granted
List : 1
Adding 2
Access
Temp - 1
Temp Array:
1
List : 2 null
Adding 3
Access
Temp - 2Temp - null
Temp Array:
2
null
Replacing 1 null with 2
List : 3 2 null
Adding 66
Access
Temp - 2Temp - null
Temp Array:
2
null
Replacing 2 null with 2
List : 3 66 2 null
3 66 2 null
我不知道爲什麼它不會將「1」的溫度數組重新添加回列表後綴。誰能幫忙?