-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathMap.java
More file actions
90 lines (76 loc) · 2.08 KB
/
Map.java
File metadata and controls
90 lines (76 loc) · 2.08 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
import java.util.ArrayList;
class Map {
private ArrayList<Entry> entries;
private int size;
private int capacity;
private static final int INITIAL_CAPACITY = 10;
public Map() {
this.entries = new ArrayList<>();
this.size = 0;
this.capacity = INITIAL_CAPACITY;
}
// 重新分配容量
private void resizeMap(int newCapacity) {
this.capacity = newCapacity;
}
// 插入键值对(如果存在则更新)
public void put(String key, int value) {
for (Entry entry : entries) {
if (entry.key.equals(key)) {
entry.value = value; // 更新值
return;
}
}
if (size >= capacity) {
resizeMap(capacity * 2);
}
entries.add(new Entry(key, value));
size++;
}
// 查找键
public int get(String key) {
for (Entry entry : entries) {
if (entry.key.equals(key)) {
return entry.value;
}
}
return -1; // 未找到
}
// 删除键
public void delete(String key) {
for (int i = 0; i < size; i++) {
if (entries.get(i).key.equals(key)) {
entries.remove(i);
size--;
return;
}
}
}
private static class Entry {
String key;
int value;
Entry(String key, int value) {
this.key = key;
this.value = value;
}
}
public static void main(String[] args) {
Map map = new Map();
map.put("apple", 10);
map.put("banana", 20);
map.put("orange", 30);
System.out.println("apple: " + map.get("apple"));
System.out.println("banana: " + map.get("banana"));
System.out.println("grape: " + map.get("grape"));
map.delete("banana");
System.out.println("banana after delete: " + map.get("banana"));
}
}
/*
* jarry@MacBook-Pro map % javac Map.java
* jarry@MacBook-Pro map % java Map
* apple: 10
* banana: 20
* grape: -1
* banana after delete: -1
*/