【问题标题】:Why doesn't ArrayDeque implement List?为什么 ArrayDeque 不实现 List?
【发布时间】:2023-04-01 16:35:01
【问题描述】:

我目前想要一个像带索引的双端队列一样的数据结构。 所以,它应该有 O(1) 的前后元素的添加和删除,以及基于索引的元素的 O(1) 访问。不难想象有什么设置可以解决这个问题。

ArrayDeque 似乎是一个自然的选择。但是,ArrayDeque 没有实现 List。既然底层的数据结构是一个数组,那它不允许索引有很好的理由吗?

另外,在更实际的情况下,有没有人知道有任何图书馆在做我想做的事情。据我所知,Apache Commons 没有。

【问题讨论】:

  • 我不知道答案,但数组肯定没有O(1) 附加属性,因为它们的大小是固定的。链表可以,但它们没有 O(1) 按索引访问。
  • 当你在一个数组中伪造它时,你会在那里添加一些间隙。所以你有一个数组,它在内存中有 100 个项目,但存储在数组中 45-57 左右的位置。然后您可以按顺序在正面和背面添加项目 1 次。直到你的空间用完为止。然后你放弃它并制作一个新数组。这听起来有点奇怪,但是数组的内存空间非常有效,它基本上总是优于链表。事实上,即使是链表最适合的事情,大多数事情都会执行链表,这仅仅是因为内存喜欢数组(缓存、额外加载数据等)。
  • 其实可以这样实现队列和栈,在需要的时候直接循环回零或者.length,然后只有当大小超过你的数组大小时才重建队列正在使用。由于内存喜欢数组,因此您可以从中获得很多比链接列表更好的性能,而链接列表会不断错过缓存查找。
  • 还有一个 OpenJDK Jira 票证:(coll) retrofit ArrayDeque to implement List

标签: java data-structures


【解决方案1】:

(编辑,原来的答案大多是错误的)

这个类没有索引没有充分的理由。我检查了源代码。它的运行方式与我上面建议的完全一样。其他一些项目可能更难在 List 界面中添加。但是,简单的 get 不会是其中之一。

根据您的使用情况,您可以使用给定大小的数组。然后将起始位置设置到它的一半。然后跟踪头部和尾部的变量。当您迭代项目时,您将头部向后移动,尾部向前向外扩展。如果您需要一个超出范围的值,则对该值取模,因此 .length 等于 0,-1 等于 (.length -1) 并且您继续添加值直到 ((tail - head) > .length) 在哪一点你建立另一个数组复制所有的部分是一致的,通常是大小的两倍。然后索引它,你用 head +index 得到真正的索引。

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/ArrayDeque.java

很确定 get 类似于:

    @Override
    public E get(int index) {
        int i = (head + index) & (elements.length - 1);
        return elements[i];
    }

似乎他们几乎肯定应该拥有它。 (请参阅源代码链接以获取以下许可信息)。

import java.io.*;
import java.util.AbstractCollection;
import java.util.Arrays;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;

public class ArrayDequeList<E>  extends AbstractCollection<E>  implements Deque<E>, Cloneable, Serializable, List<E>
{
    private transient E[] elements;
    private transient int head;
    private transient int tail;
    private static final int MIN_INITIAL_CAPACITY = 8;

    private void allocateElements(int numElements) {
        int initialCapacity = MIN_INITIAL_CAPACITY;
        // Find the best power of two to hold elements.
        // Tests "<=" because arrays aren't kept full.
        if (numElements >= initialCapacity) {
            initialCapacity = numElements;
            initialCapacity |= (initialCapacity >>>  1);
            initialCapacity |= (initialCapacity >>>  2);
            initialCapacity |= (initialCapacity >>>  4);
            initialCapacity |= (initialCapacity >>>  8);
            initialCapacity |= (initialCapacity >>> 16);
            initialCapacity++;

            if (initialCapacity < 0)   // Too many elements, must back off
                initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
        }
        elements = (E[]) new Object[initialCapacity];
    }

    @Override
    public boolean addAll(int index, @NonNull Collection<? extends E> c) {
        return false;
    }

    @Override
    public E get(int index) {
        int i = (head + index) & (elements.length - 1);
        return elements[i];
    }

    @Override
    public E set(int index, E element) {
        int i = (head + index) & (elements.length - 1);
        E old = elements[i];
        elements[i] = element;
        return old;
    }

    @Override
    public void add(int index, E element) {
        throw new IllegalStateException("This one is hard to do.");
    }

    @Override
    public E remove(int index) {
        throw new IllegalStateException("This one is hard to do.");
    }

    @Override
    public int indexOf(Object o) {
        throw new IllegalStateException("This one's not that hard but pass..");
    }

    @Override
    public int lastIndexOf(Object o) {
        throw new IllegalStateException("This one's not that hard but pass..");
    }

    @Override
    public ListIterator<E> listIterator() {
        throw new IllegalStateException("Needs to write a new iterator..");
    }

    @NonNull
    @Override
    public ListIterator<E> listIterator(int index) {
        throw new IllegalStateException("Needs to write a new iterator..");
    }

    @NonNull
    @Override
    public List<E> subList(int fromIndex, int toIndex) {
        throw new IllegalStateException("Hm, not sure how this would work.");
    }

    private void doubleCapacity() {
        assert head == tail;
        int p = head;
        int n = elements.length;
        int r = n - p; // number of elements to the right of p
        int newCapacity = n << 1;
        if (newCapacity < 0)
            throw new IllegalStateException("Sorry, deque too big");
        Object[] a = new Object[newCapacity];
        System.arraycopy(elements, p, a, 0, r);
        System.arraycopy(elements, 0, a, r, p);
        elements = (E[])a;
        head = 0;
        tail = n;
    }

    private <T> T[] copyElements(T[] a) {
        if (head < tail) {
            System.arraycopy(elements, head, a, 0, size());
        } else if (head > tail) {
            int headPortionLen = elements.length - head;
            System.arraycopy(elements, head, a, 0, headPortionLen);
            System.arraycopy(elements, 0, a, headPortionLen, tail);
        }
        return a;
    }

    public ArrayDequeList() {
        elements = (E[]) new Object[16];
    }

    public ArrayDequeList(int numElements) {
        allocateElements(numElements);
    }

    public ArrayDequeList(Collection<? extends E> c) {
        allocateElements(c.size());
        addAll(c);
    }


    public void addFirst(E e) {
        if (e == null)
            throw new NullPointerException();
        elements[head = (head - 1) & (elements.length - 1)] = e;
        if (head == tail)
            doubleCapacity();
    }

    public void addLast(E e) {
        if (e == null)
            throw new NullPointerException();
        elements[tail] = e;
        if ( (tail = (tail + 1) & (elements.length - 1)) == head)
            doubleCapacity();
    }

    public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }

    public boolean offerLast(E e) {
        addLast(e);
        return true;
    }

    public E removeFirst() {
        E x = pollFirst();
        if (x == null)
            throw new NoSuchElementException();
        return x;
    }

    public E removeLast() {
        E x = pollLast();
        if (x == null)
            throw new NoSuchElementException();
        return x;
    }

    public E pollFirst() {
        int h = head;
        E result = elements[h]; // Element is null if deque empty
        if (result == null)
            return null;
        elements[h] = null;     // Must null out slot
        head = (h + 1) & (elements.length - 1);
        return result;
    }

    public E pollLast() {
        int t = (tail - 1) & (elements.length - 1);
        E result = elements[t];
        if (result == null)
            return null;
        elements[t] = null;
        tail = t;
        return result;
    }

    public E getFirst() {
        E x = elements[head];
        if (x == null)
            throw new NoSuchElementException();
        return x;
    }

    public E getLast() {
        E x = elements[(tail - 1) & (elements.length - 1)];
        if (x == null)
            throw new NoSuchElementException();
        return x;
    }

    public E peekFirst() {
        return elements[head]; // elements[head] is null if deque empty
    }

    public E peekLast() {
        return elements[(tail - 1) & (elements.length - 1)];
    }

    public boolean removeFirstOccurrence(Object o) {
        if (o == null)
            return false;
        int mask = elements.length - 1;
        int i = head;
        E x;
        while ( (x = elements[i]) != null) {
            if (o.equals(x)) {
                delete(i);
                return true;
            }
            i = (i + 1) & mask;
        }
        return false;
    }

    public boolean removeLastOccurrence(Object o) {
        if (o == null)
            return false;
        int mask = elements.length - 1;
        int i = (tail - 1) & mask;
        E x;
        while ( (x = elements[i]) != null) {
            if (o.equals(x)) {
                delete(i);
                return true;
            }
            i = (i - 1) & mask;
        }
        return false;
    }


    public boolean add(E e) {
        addLast(e);
        return true;
    }


    public boolean offer(E e) {
        return offerLast(e);
    }

    public E remove() {
        return removeFirst();
    }


    public E poll() {
        return pollFirst();
    }

    public E element() {
        return getFirst();
    }


    public E peek() {
        return peekFirst();
    }

    public void push(E e) {
        addFirst(e);
    }

    public E pop() {
        return removeFirst();
    }

    private void checkInvariants() {
        assert elements[tail] == null;
        assert head == tail ? elements[head] == null :
                (elements[head] != null &&
                        elements[(tail - 1) & (elements.length - 1)] != null);
        assert elements[(head - 1) & (elements.length - 1)] == null;
    }

    private boolean delete(int i) {
        checkInvariants();
        final E[] elements = this.elements;
        final int mask = elements.length - 1;
        final int h = head;
        final int t = tail;
        final int front = (i - h) & mask;
        final int back  = (t - i) & mask;

        // Invariant: head <= i < tail mod circularity
        if (front >= ((t - h) & mask))
            throw new ConcurrentModificationException();

        // Optimize for least element motion
        if (front < back) {
            if (h <= i) {
                System.arraycopy(elements, h, elements, h + 1, front);
            } else { // Wrap around
                System.arraycopy(elements, 0, elements, 1, i);
                elements[0] = elements[mask];
                System.arraycopy(elements, h, elements, h + 1, mask - h);
            }
            elements[h] = null;
            head = (h + 1) & mask;
            return false;
        } else {
            if (i < t) { // Copy the null tail as well
                System.arraycopy(elements, i + 1, elements, i, back);
                tail = t - 1;
            } else { // Wrap around
                System.arraycopy(elements, i + 1, elements, i, mask - i);
                elements[mask] = elements[0];
                System.arraycopy(elements, 1, elements, 0, t);
                tail = (t - 1) & mask;
            }
            return true;
        }
    }

    public int size() {
        return (tail - head) & (elements.length - 1);
    }

    public boolean isEmpty() {
        return head == tail;
    }

    public Iterator<E> iterator() {
        return new DeqIterator();
    }

    public Iterator<E> descendingIterator() {
        return new DescendingIterator();
    }

    private class DeqIterator implements Iterator<E> {

        private int cursor = head;

        private int fence = tail;

        private int lastRet = -1;

        public boolean hasNext() {
            return cursor != fence;
        }

        public E next() {
            if (cursor == fence)
                throw new NoSuchElementException();
            E result = elements[cursor];
            // This check doesn't catch all possible comodifications,
            // but does catch the ones that corrupt traversal
            if (tail != fence || result == null)
                throw new ConcurrentModificationException();
            lastRet = cursor;
            cursor = (cursor + 1) & (elements.length - 1);
            return result;
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            if (delete(lastRet)) { // if left-shifted, undo increment in next()
                cursor = (cursor - 1) & (elements.length - 1);
                fence = tail;
            }
            lastRet = -1;
        }
    }

    private class DescendingIterator implements Iterator<E> {

        private int cursor = tail;
        private int fence = head;
        private int lastRet = -1;

        public boolean hasNext() {
            return cursor != fence;
        }

        public E next() {
            if (cursor == fence)
                throw new NoSuchElementException();
            cursor = (cursor - 1) & (elements.length - 1);
            E result = elements[cursor];
            if (head != fence || result == null)
                throw new ConcurrentModificationException();
            lastRet = cursor;
            return result;
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            if (!delete(lastRet)) {
                cursor = (cursor + 1) & (elements.length - 1);
                fence = head;
            }
            lastRet = -1;
        }
    }

    public boolean contains(Object o) {
        if (o == null)
            return false;
        int mask = elements.length - 1;
        int i = head;
        E x;
        while ( (x = elements[i]) != null) {
            if (o.equals(x))
                return true;
            i = (i + 1) & mask;
        }
        return false;
    }

    public boolean remove(Object o) {
        return removeFirstOccurrence(o);
    }

    public void clear() {
        int h = head;
        int t = tail;
        if (h != t) { // clear all cells
            head = tail = 0;
            int i = h;
            int mask = elements.length - 1;
            do {
                elements[i] = null;
                i = (i + 1) & mask;
            } while (i != t);
        }
    }


    public Object[] toArray() {
        return copyElements(new Object[size()]);
    }

    public <T> T[] toArray(T[] a) {
        int size = size();
        if (a.length < size)
            a = (T[])java.lang.reflect.Array.newInstance(
                    a.getClass().getComponentType(), size);
        copyElements(a);
        if (a.length > size)
            a[size] = null;
        return a;
    }


    public ArrayDequeList<E> clone() {
        try {
            ArrayDequeList<E> result = (ArrayDequeList<E>) super.clone();
            result.elements = Arrays.copyOf(elements, elements.length);
            return result;

        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }

    private static final long serialVersionUID = 2340785798034038923L;

    private void writeObject(ObjectOutputStream s) throws IOException {
        s.defaultWriteObject();

        // Write out size
        s.writeInt(size());

        // Write out elements in order.
        int mask = elements.length - 1;
        for (int i = head; i != tail; i = (i + 1) & mask)
            s.writeObject(elements[i]);
    }

    private void readObject(ObjectInputStream s)
            throws IOException, ClassNotFoundException {
        s.defaultReadObject();

        // Read in size and allocate array
        int size = s.readInt();
        allocateElements(size);
        head = 0;
        tail = size;

        // Read in all elements in the proper order.
        for (int i = 0; i < size; i++)
            elements[i] = (E)s.readObject();
    }
}

【讨论】:

  • 也许我遗漏了一些东西,但我没有得到最后一个论点。找到第 i 个项目的存储位置只需将 tail 添加到其中并将其与后备数组的长度减一进行与运算,没什么大不了的,当然也不是线性时间算法
  • 有时如果你允许就地插入,你会在那里留下一些空隙。所以它就像一个字典插入。您将一两本书推下线的地方。您可以在不复制所有数据的情况下合理插入项目。
  • 但是 ArrayDeque 并不稀疏,它只是一个普通的旧的二次幂大小的圆形数组
  • ArrayDeque 的功能与插入的 ArrayList 有什么不同吗?
  • listIterator 是最棘手的,因为它不仅仅是一个简单的迭代器,它是一个具有addsetremove 方法的双向walker。
猜你喜欢
  • 2019-06-17
  • 1970-01-01
  • 1970-01-01
  • 2011-09-04
  • 2014-09-29
  • 2018-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多