-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNativeDictionary.java
More file actions
99 lines (91 loc) · 2.72 KB
/
NativeDictionary.java
File metadata and controls
99 lines (91 loc) · 2.72 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
import java.lang.reflect.Array;
class NativeDictionary<T> {
public int size;
public String[] slots;
public T[] values;
public NativeDictionary(int sz, Class clazz) {
size = sz;
slots = new String[size];
values = (T[]) Array.newInstance(clazz, this.size);
}
public int hashFun(String key) {
// всегда возвращает корректный индекс слота
int result = 0;
for (int i = 0; i < key.length(); i++) {
result += (int) key.charAt(i);
}
result %= size;
return result;
}
public boolean isKey(String key) {
// возвращает true если ключ имеется,
// иначе false
int times = 0;
int counter = hashFun(key);
while (slots[counter] != null) {
if (slots[counter].equals(key)) {
return true;
}
counter += 3;
counter %= size;
times++;
if (times == size) {
return false;
}
}
return false;
}
public void put(String key, T value) {
// гарантированно записываем
// значение value по ключу key
int counter = hashFun(key);
int isEmpty = isEmpty(slots);
if (isEmpty != 0) {
while (slots[counter] != null && !values[counter].equals(value)) {
counter += 3;
counter %= size;
}
slots[counter] = key;
values[counter] = value;
}
}
public int isEmpty(String[] array) {
int amount = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == null) {
amount++;
}
}
return amount;
}
public T get(String key) {
// возвращает value для key,
// или null если ключ не найден
int counter = hashFun(key);
int times = 0;
while (slots[counter] != null) {
if (slots[counter].equals(key)) {
return values[counter];
}
counter += 3;
counter %= size;
times++;
if (times == size) {
return null;
}
}
return null;
}
public void display() {
System.out.println("Slots:");
for (int i = 0; i < size; i++) {
System.out.print("| " + slots[i] + " ");
}
System.out.println("|");
System.out.println("Values");
for (int i = 0; i < size; i++) {
System.out.print("| " + values[i] + " ");
}
System.out.println("|");
}
}