Royan said:
I'm looking for the collection with following properties.
- Contains no duplicate elements
- Has push/pop (offer/poll) like methods
- Insertion order does not matter
The best I could find was TreeSet but it maintains ordering which
produced log(n) overhead for add/remove operations. As far as this is
not that critical for me I'll eventually use TreeSet, but perhaps
someone knows some other collection that does not maintain order of
elements and at the same time has all those characteristics I've
listed above?
Took me 20 minutes:
Public domain, no warranty.
import java.util.*;
/**
š * @author Daniel Pitts
š */
public class UniqueQueue<T> implements Queue<T>, Set<T> {
š š šprivate final Set<T> data = new LinkedHashSet<T>();
š š špublic int size() {
š š š š šreturn data.size();
š š š}
š š špublic boolean isEmpty() {
š š š š šreturn data.isEmpty();
š š š}
š š špublic boolean contains(Object o) {
š š š š šreturn data.contains(o);
š š š}
š š špublic Iterator<T> iterator() {
š š š š šreturn data.iterator();
š š š}
š š špublic Object[] toArray() {
š š š š šreturn data.toArray();
š š š}
š š špublic <T> T[] toArray(T[] a) {
š š š š šreturn data.toArray(a);
š š š}
š š špublic boolean add(T t) {
š š š š šreturn data.add(t);
š š š}
š š špublic boolean offer(T t) {
š š š š šreturn add(t);
š š š}
š š špublic T remove() {
š š š š šfinal Iterator<T> iterator = data.iterator();
š š š š šT t = iterator.next();
š š š š šiterator.remove();
š š š š šreturn t;
š š š}
š š špublic T poll() {
š š š š šfinal Iterator<T> iterator = data.iterator();
š š š š šif (iterator.hasNext()) {
š š š š š š šT t = iterator.next();
š š š š š š šiterator.remove();
š š š š š š šreturn t;
š š š š š}
š š š š šreturn null;
š š š}
š š špublic T element() {
š š š š šreturn data.iterator().next();
š š š}
š š špublic T peek() {
š š š š šfinal Iterator<T> iterator = data.iterator();
š š š š šif (iterator.hasNext()) {
š š š š š š šreturn iterator.next();
š š š š š}
š š š š šreturn null;
š š š}
š š špublic boolean remove(Object o) {
š š š š šreturn data.remove(o);
š š š}
š š špublic boolean containsAll(Collection<?> c) {
š š š š šreturn data.containsAll(c);
š š š}
š š špublic boolean addAll(Collection<? extends T> c) {
š š š š šreturn data.addAll(c);
š š š}
š š špublic boolean retainAll(Collection<?> c) {
š š š š šreturn data.retainAll(c);
š š š}
š š špublic boolean removeAll(Collection<?> c) {
š š š š šreturn data.removeAll(c);
š š š}
š š špublic void clear() {
š š š š šdata.clear();
š š š}
š š špublic boolean equals(Object o) {
š š š š šreturn data.equals(o);
š š š}
š š špublic int hashCode() {
š š š š šreturn data.hashCode();
š š š}
}