-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashmap.java
69 lines (66 loc) · 1.54 KB
/
Hashmap.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
*
* @function:to implement hashmap in my own
* @ get and put, the structure of a map
* we have an array of linked list and take hash value as the identifier(index)
*
*/
public class hashmap {
private final static int SIZE = 16; // initial size, could be resized later
private Entry[] table = new Entry[SIZE]; // array
// entry is actually a linked list with a next "pointer"
class Entry{
final String key; // better not to change the key
String value;
Entry nextEntry;
public Entry(String k, String v) {
key = k;
value = v;
}
public String getKey(){
return key;
}
public String getValue(){
return value;
}
public void setValue(String v){
this.value = v;
}
}
public Entry get(String k){
int hash = k.hashCode() % SIZE;
Entry entry = table[hash];
while(entry != null){
if(entry.key.equals(k)){
return entry;
}
entry = entry.nextEntry;
}
return null;
}
public void put(String k, String v){
int hash = k.hashCode() % SIZE;
Entry entry = table[hash];
if(entry != null){
if(entry.key.equals(k)){
entry.value = v;
}else{
while(entry.nextEntry != null){
entry = entry.nextEntry;
}// reach the end of the list
Entry newEntry = new Entry(k, v);
entry.nextEntry = newEntry;
}
}else{
Entry newEntry = new Entry(k, v);
table[hash] = newEntry;
}
}
public static void main(String[] args){
hashmap hm = new hashmap();
hm.put("ning", "needs");
hm.put("dan", "lover");
hm.put("wei", "rivals");
System.out.println(hm.get("ning").getKey());
}
}