Creating a queue that does not allow duplicate items and should allow index-based searches

I want to create a queue that should not allow duplicate elements, and I should have access to the elements of this queue based on the index. Please let me know how to implement this?

+4
source share
4 answers

I plan to use ConcurrentLinkedQueue for my problem. Here is a sample code

import java.util.concurrent.ConcurrentLinkedQueue; public class FinalQueue { private ConcurrentLinkedQueue<String> queue; public FinalQueue() { queue = new ConcurrentLinkedQueue<String>(); } public synchronized void enqueue(String ipAddress) { if(!queue.contains(ipAddress)) queue.add(ipAddress); } public String dequeue() { return queue.poll(); } public String toString() { return "" + queue; } /** * @param args */ public static void main(String[] args) { FinalQueue queue = new FinalQueue(); queue.enqueue("1.2.3.4"); queue.enqueue("2.3.4.5"); queue.enqueue("1.1.1.1"); queue.enqueue("1.2.3.4"); System.out.println(queue.toString()); System.out.println("Dequeue..." + queue.dequeue()); System.out.println("Dequeue..." + queue.dequeue()); System.out.println(queue.toString()); } } 
+1
source

Well, it is clear that Java does not have an exact data structure that matches your specification and requirement. The closest that can meet your requirements is probably LinkedHashSet . This is basically a collection (corresponding to your unique requirement for elements), whose elements are stored in input order (for example, in a queue), and to get an element by index, you can use set.toArray() to get an array or create a list from the set (however this will require additional additional memory).

+5
source

You can always use ArrayList. This is useful for accessing index-based elements, and when adding elements, you can always simply check if the ArrayList contains the element to be added. My initial instinct was to use Set to prevent duplicates, but the elements are Sets that are not indexed. If you can find a way to index elements in sets, then this will be my recommendation.

0
source

Do not call this a queue, because by definition, a queue is only the first in the first data structure.

Depending on your input values, I believe that you should use an array and a hash function. The hash determines which index the element is located using its value, and vice versa, i.e. When specifying an index, it returns the value contained in it.

Since you use a hash, repetition is avoided in a collision, that is, you can check if a value previously existed in the index and if it has the same value or not.

C ++ stl has a nice class to set up, although java I don't think it is. But the point is set, it does not offer index search.

0
source

All Articles