1 33 34 package edu.rice.cs.util; 35 import java.util.*; 36 37 39 40 public class OrderedHashSet<Type> implements Collection<Type> { 41 private HashSet<Type> elements = new HashSet<Type>(); 42 private ArrayList<Type> order = new ArrayList<Type>(); 43 44 45 46 public boolean add(Type elt) { 47 boolean validAdd = elements.add(elt); 48 if (validAdd) order.add(elt); 49 return validAdd; 50 } 51 52 public boolean addAll(Collection<? extends Type> c) { 53 throw new UnsupportedOperationException ("OrderedHashSet does not support this operation"); 54 } 55 56 public void clear() { 57 elements.clear(); 58 order.clear(); 59 } 60 61 public boolean contains(Object elt) { return elements.contains(elt); } 62 63 public boolean containsAll(Collection<?> c) { 64 throw new UnsupportedOperationException ("OrderedHashSet does not support this operation"); 65 } 66 67 public boolean equals(Object o) { 68 if ((o == null) || o.getClass() != getClass()) return false; 69 return order.equals(elements()); 70 } 71 72 public int hashCode() { return order.hashCode(); } 73 74 public boolean isEmpty() { return order.isEmpty(); } 75 76 public Type get(int i) { return order.get(i); } 77 78 public Iterator<Type> iterator() { return new OHMIterator(); } 79 80 81 public Type remove(int i) { 82 Type elt = order.remove(i); elements.remove(elt); 84 return elt; 85 } 86 87 public boolean remove(Object elt) { 88 elements.remove(elt); 89 return order.remove(elt); } 91 92 public boolean removeAll(Collection<?> elts) { 93 throw new UnsupportedOperationException ("OrderedHashSet does not support this operation"); 94 } 95 96 public boolean retainAll(Collection<?> elts) { 97 throw new UnsupportedOperationException ("OrderedHashSet does not support this operation"); 98 } 99 100 public int size() { return order.size(); } 101 102 public Object [] toArray() { return order.toArray(); } 103 104 public <T> T[] toArray(T[] a) { return order.toArray(a); } 105 106 public Collection<Type> elements() { return order; } 107 108 public String toString() { return order.toString(); } 109 110 111 class OHMIterator implements Iterator<Type> { 112 113 Iterator<Type> it = order.iterator(); 114 115 116 Type lastElt = null; 117 118 public boolean hasNext() { return it.hasNext(); } 119 120 public Type next() { 121 lastElt = it.next(); 122 return lastElt; 123 } 124 125 126 public void remove() { 127 it.remove(); 128 elements.remove(lastElt); 129 } 130 } 131 } 132 | Popular Tags |