A Queue that ensure uniqueness of the elements?

前端 未结 8 1309
甜味超标
甜味超标 2020-12-13 08:25

I\'m looking for a implementation of java.util.Queue or something in the Google collection who behave like a Queue, but also ensure that each element of the queue is unique.

8条回答
  •  旧时难觅i
    2020-12-13 08:43

    This doesn't exist as far as I know but would be fairly simple to implement using a LinkedList in conjunction with a Set:

    /**
     * Thread unsafe implementation of UniqueQueue.
     */
    public class UniqueQueue implements Queue {
      private final Queue queue = new LinkedList();
      private final Set set = new HashSet();
    
      public boolean add(T t) {
        // Only add element to queue if the set does not contain the specified element.
        if (set.add(t)) {
          queue.add(t);
        }
    
        return true; // Must always return true as per API def.
      }
    
      public T remove() throws NoSuchElementException {
        T ret = queue.remove();
        set.remove(ret);
        return ret;
      }
    
      // TODO: Implement other Queue methods.
    }
    

提交回复
热议问题