1 8 9 package com.sleepycat.je.utilint; 10 11 import java.util.HashSet ; 12 import java.util.Iterator ; 13 import java.util.NoSuchElementException ; 14 import java.util.Set ; 15 16 25 public class TinyHashSet { 26 27 private Set set; 28 private Object single; 29 30 33 public int size() { 34 if (single != null) { 35 return 1; 36 } else if (set != null) { 37 return set.size(); 38 } else { 39 return 0; 40 } 41 } 42 43 public boolean remove(Object o) { 44 assert (single == null) || (set == null); 45 if (single != null) { 46 if (single == o || 47 single.equals(o)) { 48 single = null; 49 return true; 50 } else { 51 return false; 52 } 53 } else if (set != null) { 54 return set.remove(o); 55 } else { 56 return false; 57 } 58 } 59 60 public boolean add(Object o) { 61 assert (single == null) || (set == null); 62 if (set != null) { 63 return set.add(o); 64 } else if (single == null) { 65 single = o; 66 return true; 67 } else { 68 set = new HashSet (); 69 set.add(single); 70 single = null; 71 return set.add(o); 72 } 73 } 74 75 public Set copy() { 76 assert (single == null) || (set == null); 77 if (set != null) { 78 return new HashSet (set); 79 } else { 80 Set ret = new HashSet (); 81 if (single != null) { 82 ret.add(single); 83 } 84 return ret; 85 } 86 } 87 88 public Iterator iterator() { 89 assert (single == null) || (set == null); 90 if (set != null) { 91 return set.iterator(); 92 } else { 93 return new SingleElementIterator(single, this); 94 } 95 } 96 97 100 public static class SingleElementIterator implements Iterator { 101 Object theObject; 102 TinyHashSet theSet; 103 boolean returnedTheObject = false; 104 105 SingleElementIterator(Object o, TinyHashSet theSet) { 106 theObject = o; 107 this.theSet = theSet; 108 returnedTheObject = (o == null); 109 } 110 111 public boolean hasNext() { 112 return !returnedTheObject; 113 } 114 115 public Object next() { 116 if (returnedTheObject) { 117 throw new NoSuchElementException (); 118 } 119 120 returnedTheObject = true; 121 return theObject; 122 } 123 124 public void remove() { 125 if (theObject == null || 126 !returnedTheObject) { 127 throw new IllegalStateException (); 128 } 129 theSet.remove(theObject); 130 } 131 } 132 } 133 | Popular Tags |