1 11 package org.eclipse.jdt.internal.compiler.codegen; 12 13 public class ObjectCache { 14 public Object keyTable[]; 15 public int valueTable[]; 16 int elementSize; 17 int threshold; 18 22 public ObjectCache() { 23 this(13); 24 } 25 31 public ObjectCache(int initialCapacity) { 32 this.elementSize = 0; 33 this.threshold = (int) (initialCapacity * 0.66f); 34 this.keyTable = new Object [initialCapacity]; 35 this.valueTable = new int[initialCapacity]; 36 } 37 40 public void clear() { 41 for (int i = this.keyTable.length; --i >= 0;) { 42 this.keyTable[i] = null; 43 this.valueTable[i] = 0; 44 } 45 this.elementSize = 0; 46 } 47 52 public boolean containsKey(Object key) { 53 int index = hashCode(key), length = this.keyTable.length; 54 while (this.keyTable[index] != null) { 55 if (this.keyTable[index] == key) 56 return true; 57 if (++index == length) { 58 index = 0; 59 } 60 } 61 return false; 62 } 63 69 public int get(Object key) { 70 int index = hashCode(key), length = this.keyTable.length; 71 while (this.keyTable[index] != null) { 72 if (this.keyTable[index] == key) 73 return this.valueTable[index]; 74 if (++index == length) { 75 index = 0; 76 } 77 } 78 return -1; 79 } 80 86 public int hashCode(Object key) { 87 return (key.hashCode() & 0x7FFFFFFF) % this.keyTable.length; 88 } 89 98 public int put(Object key, int value) { 99 int index = hashCode(key), length = this.keyTable.length; 100 while (this.keyTable[index] != null) { 101 if (this.keyTable[index] == key) 102 return this.valueTable[index] = value; 103 if (++index == length) { 104 index = 0; 105 } 106 } 107 this.keyTable[index] = key; 108 this.valueTable[index] = value; 109 110 if (++this.elementSize > this.threshold) 112 rehash(); 113 return value; 114 } 115 120 private void rehash() { 121 ObjectCache newHashtable = new ObjectCache(this.keyTable.length * 2); 122 for (int i = this.keyTable.length; --i >= 0;) 123 if (this.keyTable[i] != null) 124 newHashtable.put(this.keyTable[i], this.valueTable[i]); 125 126 this.keyTable = newHashtable.keyTable; 127 this.valueTable = newHashtable.valueTable; 128 this.threshold = newHashtable.threshold; 129 } 130 135 public int size() { 136 return this.elementSize; 137 } 138 143 public String toString() { 144 int max = size(); 145 StringBuffer buf = new StringBuffer (); 146 buf.append("{"); for (int i = 0; i < max; ++i) { 148 if (this.keyTable[i] != null) { 149 buf.append(this.keyTable[i]).append("->").append(this.valueTable[i]); } 151 if (i < max) { 152 buf.append(", "); } 154 } 155 buf.append("}"); return buf.toString(); 157 } 158 } 159 | Popular Tags |