-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashMap.java
More file actions
104 lines (93 loc) · 2.44 KB
/
HashMap.java
File metadata and controls
104 lines (93 loc) · 2.44 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
public class HashMapCustom {
private static final int default_capacity = 7;
private int capacity;
private int size;
private Entry[] table;
private static class Entry {
String key;
int value;
Entry(String key, int value) {
this.key = key;
this.value = value;
}
}
public HashMapCustom(int capacity) {
this.capacity = capacity;
table = new Entry[capacity];
size = 0;
}
public HashMapCustom() {
this(default_capacity);
}
private int hash(String key) {
return Math.abs(key.hashCode()) % capacity;
}
public boolean put(String key, int value) {
if (size == capacity) {
return false;
}
int index = hash(key);
while (table[index] != null && !table[index].key.equals(key)) {
index = (index + 1) % capacity;
}
if (table[index] == null) {
size++;
}
table[index] = new Entry(key, value);
return true;
}
public int get(String key) {
int index = hash(key);
int start = index;
while (table[index] != null) {
if (table[index].key.equals(key)) {
return table[index].value;
}
index = (index + 1) % capacity;
if (index == start) {
break;
}
}
return 0;
}
public boolean containsKey(String key) {
int index = hash(key);
int start = index;
while (table[index] != null) {
if (table[index].key.equals(key)) {
return true;
}
index = (index + 1) % capacity;
if (index == start) {
break;
}
}
return false;
}
public boolean remove(String key) {
int index = hash(key);
int start = index;
while (table[index] != null) {
if (table[index].key.equals(key)) {
table[index] = null;
size--;
return true;
}
index = (index + 1) % capacity;
if (index == start) {
break;
}
}
return false;
}
public void clear() {
table = new Entry[capacity];
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == capacity;
}
}