Best implementation of Java Queue?

后端 未结 9 723
有刺的猬
有刺的猬 2020-12-23 16:23

I am working (in Java) on a recursive image processing algorithm that recursively traverses the pixels of the image, outwards from a center point.

Unfortunately, tha

9条回答
  •  爱一瞬间的悲伤
    2020-12-23 16:36

    If you use LinkedList be careful. If you use it like this:

    LinkedList queue = new LinkedList();
    

    then you can violate queue definition, because it is possible to remove other elements than first (there are such methods in LinkedList).

    But if you use it like this:

    Queue queue = new LinkedList();
    

    it should be ok,as this is heads-up to users that insertions should occur only at the back and deletions only at the front.

    You can overcome defective implementation of the Queue interface by extending the LinkedList class to a PureQueue class that throws UnsupportedOperationException of any of the offending methods. Or you can take approach with aggreagation by creating PureQueue with only one field which is type LinkedList object, list, and the only methods will be a default constructor, a copy constructor, isEmpty(), size(), add(E element), remove(), and element(). All those methods should be one-liners, as for example:

    /**
    * Retrieves and removes the head of this queue.
    * The worstTime(n) is constant and averageTime(n) is constant.
    *
    * @return the head of this queue.
    * @throws NoSuchElementException if this queue is empty.
    */
    public E remove()
    {
        return list.removeFirst();
    } // method remove()
    

提交回复
热议问题