Like commentators, you are more describing a particular type of Set than Queue . As far as I understand, your requirements are:
- Iteration of insertion order
- Each item in the collection is unique (not equal)
- Previously seen items can never be added again.
The first two requirements are well served by LinkedHashSet , for example this question . The latter requirement is much stranger and requires some internal storage of previously seen values. Sort of:
public class SeenOnceLinkedHashSet<E> implements Set<E> { private LinkedHashSet<E> data; private HashSet<E> seen; public boolean add(E e) { boolean newValue = seen.add(e); if (newValue) { return data.add(e); }
Note that this class has unlimited internal memory. You could easily cause a memory shortage problem using this class, as it would handle another Set without any problems. If you need the concept of "ever added," this is inevitable. You could use something more elegant like BloomFilter , but that would create false positives.
Personally, I am reviewing your requirements. Any data structure of unlimited space is almost certainly a code smell. Can you, for example, use a wrapper class that provides a more useful definition of .equals() ? Or add additional security checks when building an object, so bad objects are not built in the first place?
source share