1 11 package org.eclipse.jdt.internal.core.util; 12 13 18 public final class SimpleSet implements Cloneable { 19 20 public Object [] values; 22 public int elementSize; public int threshold; 24 25 public SimpleSet() { 26 this(13); 27 } 28 29 public SimpleSet(int size) { 30 if (size < 3) size = 3; 31 this.elementSize = 0; 32 this.threshold = size + 1; this.values = new Object [2 * size + 1]; 34 } 35 36 public Object add(Object object) { 37 int length = values.length; 38 int index = (object.hashCode() & 0x7FFFFFFF) % length; 39 Object current; 40 while ((current = values[index]) != null) { 41 if (current.equals(object)) return values[index] = object; 42 if (++index == length) index = 0; 43 } 44 values[index] = object; 45 46 if (++elementSize > threshold) rehash(); 48 return object; 49 } 50 51 public void clear() { 52 for (int i = this.values.length; --i >= 0;) 53 this.values[i] = null; 54 this.elementSize = 0; 55 } 56 57 public Object clone() throws CloneNotSupportedException { 58 SimpleSet result = (SimpleSet) super.clone(); 59 result.elementSize = this.elementSize; 60 result.threshold = this.threshold; 61 62 int length = this.values.length; 63 result.values = new Object [length]; 64 System.arraycopy(this.values, 0, result.values, 0, length); 65 return result; 66 } 67 68 public boolean includes(Object object) { 69 int length = values.length; 70 int index = (object.hashCode() & 0x7FFFFFFF) % length; 71 Object current; 72 while ((current = values[index]) != null) { 73 if (current.equals(object)) return true; 74 if (++index == length) index = 0; 75 } 76 return false; 77 } 78 79 public Object remove(Object object) { 80 int length = values.length; 81 int index = (object.hashCode() & 0x7FFFFFFF) % length; 82 Object current; 83 while ((current = values[index]) != null) { 84 if (current.equals(object)) { 85 elementSize--; 86 Object oldValue = values[index]; 87 values[index] = null; 88 if (values[index + 1 == length ? 0 : index + 1] != null) 89 rehash(); return oldValue; 91 } 92 if (++index == length) index = 0; 93 } 94 return null; 95 } 96 97 private void rehash() { 98 SimpleSet newSet = new SimpleSet(elementSize * 2); Object current; 100 for (int i = values.length; --i >= 0;) 101 if ((current = values[i]) != null) 102 newSet.add(current); 103 104 this.values = newSet.values; 105 this.elementSize = newSet.elementSize; 106 this.threshold = newSet.threshold; 107 } 108 109 public String toString() { 110 String s = ""; Object object; 112 for (int i = 0, l = values.length; i < l; i++) 113 if ((object = values[i]) != null) 114 s += object.toString() + "\n"; return s; 116 } 117 } 118 | Popular Tags |