Concurrent Set Queue

前端 未结 7 1666
情话喂你
情话喂你 2020-12-05 23:10

Maybe this is a silly question, but I cannot seem to find an obvious answer.

I need a concurrent FIFO queue that contains only unique values. Attempting to add a val

7条回答
  •  借酒劲吻你
    2020-12-05 23:35

    A simple answer for a queue of unique objects can be as follow:

    import java.util.concurrent.ConcurrentLinkedQueue;
    
    public class FinalQueue {
    
        class Bin {
            private int a;
            private int b;
    
            public Bin(int a, int b) {
                this.a = a;
                this.b = b;
            }
    
            @Override
            public int hashCode() {
                return a * b;
            }
    
            public String toString() {
                return a + ":" + b;
            }
    
            @Override
            public boolean equals(Object obj) {
                if (this == obj)
                    return true;
                if (obj == null)
                    return false;
                if (getClass() != obj.getClass())
                    return false;
                Bin other = (Bin) obj;
                if ((a != other.a) || (b != other.b))
                    return false;
                return true;
            }
        }
    
        private ConcurrentLinkedQueue queue;
    
        public FinalQueue() {
            queue = new ConcurrentLinkedQueue();
        }
    
        public synchronized void enqueue(Bin ipAddress) {
            if (!queue.contains(ipAddress))
                queue.add(ipAddress);
        }
    
        public Bin dequeue() {
            return queue.poll();
        }
    
        public String toString() {
            return "" + queue;
        }
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            FinalQueue queue = new FinalQueue();
            Bin a = queue.new Bin(2,6);
    
            queue.enqueue(a);
            queue.enqueue(queue.new Bin(13, 3));
            queue.enqueue(queue.new Bin(13, 3));
            queue.enqueue(queue.new Bin(14, 3));
            queue.enqueue(queue.new Bin(13, 9));
            queue.enqueue(queue.new Bin(18, 3));
            queue.enqueue(queue.new Bin(14, 7));
            Bin x= queue.dequeue();
            System.out.println(x.a);
            System.out.println(queue.toString());
            System.out.println("Dequeue..." + queue.dequeue());
            System.out.println("Dequeue..." + queue.dequeue());
            System.out.println(queue.toString());
        }
    }
    

提交回复
热议问题