我正在尝试实现自己的ArrayDeque,完全了解utils.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
答案 0 :(得分:0)
问题在于我忘记在从第一个数组拉出之前保存numberOfEntries
,因为当我之后设置索引时该变量将为0。通过创建临时int来保存它直到传输完成时解决了问题