Java Reference
In-Depth Information
53 @Override
54
public String toString() {
55
return "[" + key + ", " + value + "]" ;
56 }
57 }
58 }
L ISTING 27.2
MyHashMap.java
1 import java.util.LinkedList;
2
3 public class MyHashMap<K, V> implements MyMap<K, V> {
4
class MyHashMap
// Define the default hash-table size. Must be a power of 2
5
private static int DEFAULT_INITIAL_CAPACITY = 4 ;
default initial capacity
6
7
// Define the maximum hash-table size. 1 << 30 is same as 2^30
8
private static int MAXIMUM_CAPACITY = 1 << 30 ;
maximum capacity
9
10
// Current hash-table capacity. Capacity is a power of 2
11
private int capacity;
current capacity
12
13
// Define default load factor
14
private static float DEFAULT_MAX_LOAD_FACTOR = 0.75f ;
default load factor
15
16
// Specify a load factor used in the hash table
17
private float loadFactorThreshold;
load-factor threshold
18
19
// The number of entries in the map
20
private int size = 0 ;
size
21
22 // Hash table is an array with each cell being a linked list
23 LinkedList<MyMap.Entry<K,V>>[] table;
24
25
hash table
/** Construct a map with the default capacity and load factor */
26
public MyHashMap() {
no-arg constructor
27
this (DEFAULT_INITIAL_CAPACITY, DEFAULT_MAX_LOAD_FACTOR);
28 }
29
30 /** Construct a map with the specified initial capacity and
31 * default load factor */
32
public MyHashMap( int initialCapacity) {
constructor
33
this (initialCapacity, DEFAULT_MAX_LOAD_FACTOR);
34 }
35
36 /** Construct a map with the specified initial capacity
37 * and load factor */
38
public MyHashMap( int initialCapacity, float loadFactorThreshold) {
constructor
39
if (initialCapacity > MAXIMUM_CAPACITY)
40
this .capacity = MAXIMUM_CAPACITY;
41
else
42
this .capacity = trimToPowerOf2(initialCapacity);
43
44 this .loadFactorThreshold = loadFactorThreshold;
45 table = new LinkedList[capacity];
46 }
47
48 @Override /** Remove all of the entries from this map */
49 public void clear() {
50 size = 0 ;
51 removeEntries();
52 }
clear
 
 
Search WWH ::




Custom Search