forked from christine-1017/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyMap.java
More file actions
78 lines (68 loc) · 1.58 KB
/
MyMap.java
File metadata and controls
78 lines (68 loc) · 1.58 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
package datastructure;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MyMap<K, V> {
private int size;
private int DEFAULT_CAPACITY = 10;
@SuppressWarnings("unchecked")
private MapEntry<K, V>[] map = new MapEntry[DEFAULT_CAPACITY];
public V get(K key){
for(int i = 0; i < size; i++){
if(map[i] != null && map[i].getKey().equals(key)){
return map[i].getValue();
}
}
return null;
}
public void put(K key, V value) {
boolean insert = true;
for (int i = 0; i < size; i++) {
if (map[i].getKey().equals(key)) {
map[i].setValue(value);
insert = false;
}
}
if (insert) {
ensureCapacity();
map[size++] = new MapEntry<K, V>(key, value);
}
}
private void ensureCapacity() {
if (size == map.length) {
int newSize = map.length * 2;
map = Arrays.copyOf(map, newSize);
}
}
public int size(){
return size;
}
public void remove(K key){
for(int i = 0; i < size; i++){
if(map[i].getKey().equals(key)){
map[i] = null;
size--;
compactMap(i);
}
}
}
private void compactMap(int index){
for(int i = index; i < size-1; i++){
map[i] = map[i+1];
}
}
public Set<K> keySet(){
Set<K> set = new HashSet<K>();
for(int i = 0; i < size; i++){
set.add(map[i].getKey());
}
return set;
}
public static void main(String[] args) {
MyMap<String, Integer> map = new MyMap<String, Integer>();
for (int i = 0; i < 100; i++) {
map.put(String.valueOf(i), i);
}
System.out.println(map.keySet());
}
}