Reputation: 8423
I'm looking for a queue-type data structure in Java (preferably in the standard libs) which has the following properties:
remove()
operation of a queue. Obviously this fails if the structure is empty.Preserving the order of insertion/deletion isn't terribly important.
Set
structures have the no duplicates, but don't have the pop
operation, and Queue
structures don't guarantee no duplicates. Does something fitting my needs exist?
In the interests of avoiding the XY problem, I'm doing a worklist algorithm: nodes that need updating are added to the set, so I want to easily pop the next node that needs updating, and add nodes that need updating without getting a bunch of duplicates if they're already in the worklist.
Upvotes: 1
Views: 682
Reputation: 50716
You can use a set's iterator to remove a single element. The ordering will depend on the set implementation.
static <T> T remove(Set<T> set) {
Iterator<T> iter = set.iterator();
T element = iter.next();
iter.remove();
return element;
}
Upvotes: 2
Reputation: 198014
Use LinkedHashSet
, and implement pop
as
Iterator<E> iterator = set.iterator();
E result = iterator.next();
iterator.remove();
Upvotes: 5