利用可能なutils.ArrayDequeを完全に認識して、独自のArrayDequeを実装しようとしています。(これは学校のプロジェクト用です)。どうやら ArrayDeque の実用的な実装を作成しました。私の問題は、例外をスローする代わりに、いっぱいになると成長する ArrayDeque の子を作成しようとしています。成長するとインデックスは正しい (?) が、配列の順序が意味をなさない。
プロジェクトへのリンク、関連コードは以下にあります。 https://github.com/tagptroll1/Oblig1/tree/master/src/Deque
//From ResizeableArrayDeque
private void growArray(){
int newCapacity = deque.length * 2;
if (newCapacity >= MAX_CAPACITY){
throw new DequeFullException("Tried to expand deque past MAX Capacity");
}
//deque = Arrays.copyOf(deque, newCapacity);
@SuppressWarnings("unchecked")
E[] tempDeque = (E[]) new Object[newCapacity];
for (int i = deque.length; i > 0; i--){
if (!isArrayEmpty()){
tempDeque[i] = pullLast();
} else {
throw new DequeEmptyException("Tried to pull element from empty deque");
}
}
deque = tempDeque;
topIndex = 0;
botIndex = numberOfEntries;
}
@Override
public void addFirst(E elem){
if (isArrayFull()){
growArray();
}
deque[topIndex = dec(topIndex, deque.length)] = elem;
numberOfEntries ++;
}
@Override
public void addLast(E elem){
if (isArrayFull()){
growArray();
}
deque[botIndex] = elem;
numberOfEntries ++;
botIndex = inc(botIndex, deque.length);
}
// From ArrayDeque
protected static int inc(int i, int modulus) {
if (++i >= modulus) {
i = 0;
}
return i;
}
protected static int dec(int i, int modulus) {
if (--i < 0) {
i = modulus - 1;
}
return i;
}
後で追加された新しい要素では順序付けがうまくいかないため、古い配列を新しい大きな配列にコピーする方法がわかりません。配列のテスト印刷を次に示します。
Adding [a, b, c, d] to deques bottom
Adding: 0 arrayIndex to 1. tail-index, element: a
[a] [null] [4] [3] [2] [1]
Adding: 1 arrayIndex to 2. tail-index, element: b
[a] [b] [4] [3] [2] [1]
Adding: 2 arrayIndex to 1. tail-index, element: c
[c] [4] [3] [2] [1] [a] [b] [null] [null] [null] [null] [null]
Adding: 3 arrayIndex to 2. tail-index, element: d
[c] [d] [3] [2] [1] [a] [b] [null] [null] [null] [null] [null]
Current Tail index is 2