Java Reference
In-Depth Information
113
114
for
(
int
i =
0
; i < capacity; i++) {
115
if
(table[i] !=
null
) {
116 LinkedList<Entry<K, V>> bucket = table[i];
117
for
(Entry<K, V> entry: bucket)
118 set.add(entry.getKey());
119 }
120 }
121
122
return
set;
123 }
124
125 @Override
/** Add an entry (key, value) into the map */
126
public
V put(K key, V value) {
127
if
(get(key) !=
null
) {
// The key is already in the map
128
int
bucketIndex = hash(key.hashCode());
129 LinkedList<Entry<K, V>> bucket = table[bucketIndex];
130
for
(Entry<K, V> entry: bucket)
131
if
(entry.getKey().equals(key)) {
132 V oldValue = entry.getValue();
133
// Replace old value with new value
134 entry.value = value;
135
put
// Return the old value for the key
136
return
oldValue;
137 }
138 }
139
140
// Check load factor
141
if
(size >= capacity * loadFactorThreshold) {
142
if
(capacity == MAXIMUM_CAPACITY)
143
throw new
RuntimeException(
"Exceeding maximum capacity"
);
144
145 rehash();
146 }
147
148
int
bucketIndex = hash(key.hashCode());
149
150
// Create a linked list for the bucket if not already created
151
if
(table[bucketIndex] ==
null
) {
152 table[bucketIndex] =
new
LinkedList<Entry<K, V>>();
153 }
154
155
// Add a new entry (key, value) to hashTable[index]
156 table[bucketIndex].add(
new
MyMap.Entry<K, V>(key, value));
157
158 size++;
// Increase size
159
160
return
value;
161 }
162
163 @Override
/** Remove the entries for the specified key */
164
public void
remove(K key) {
remove
165
int
bucketIndex = hash(key.hashCode());
166
167
// Remove the first entry that matches the key from a bucket
168
if
(table[bucketIndex] !=
null
) {
169 LinkedList<Entry<K, V>> bucket = table[bucketIndex];
170
for
(Entry<K, V> entry: bucket)
171
if
(entry.getKey().equals(key)) {
172 bucket.remove(entry);
Search WWH ::
Custom Search