-1

我正在尝试实现我自己的 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
4

1 回答 1

0

问题在于我numberOfEntries在从第一个数组中提取之前忘记保存,因为当我之后设置索引时该变量将为 0。通过创建一个临时 int 来解决问题,直到传输完成

于 2018-02-11T18:01:18.207 回答