Mark Mark - 4 months ago 7
Java Question

Is there a Circular data structure for Java? ie CircularLinkedList

I am looking for a circular data structure to use in Java. I remember in my data structures class that there was a data structure called a CircularLinkedList.

High level:

My use case is that I need to iterate over the list until its empty. For example, consider a deck of cards. I would like to remove all 10's then all 5's then all Jacks in any order of my choosing. That is just a high level example.

Detailed:

I need to process objects that have dependencies. I cannot process an object with a field of 'B' before one of field 'A'. There is no inherent sort and I would like to get this to work and then improve later if it is even needed. I would like to process these objects out of order. If the object has a dependency that has not been processed, I would like to skip over it and loop the list until it's empty.

However, I cannot find the data structure in java. Google searches result in implementations by others, again for programming courses. Before I accept that there is no implementation for this in the Java collections, I wanted to post a question here to be certain. Afterall it could just have a name for it that I did not remember.

Answer

Your requirement seems to be this sentence:

If the object has a dependency that has not been processed, I would like to skip over it and loop the list until it's empty.

That's easy enough. You use a Queue, where you take the first value from the queue using poll(). If you cannot use the value yet, you add it back to the end of the queue using add(). You keep taking the head value until the Queue is empty, e.g. when poll() returns null.

For your purpose, an ArrayDeque is likely your best option for Queue implementation, or a LinkedList if you prefer.