-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNativeCache.java
More file actions
123 lines (113 loc) · 3.37 KB
/
NativeCache.java
File metadata and controls
123 lines (113 loc) · 3.37 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
import java.lang.reflect.Array;
class NativeCache<T>
{
public int size;
public String [] slots;
public T [] values;
public int [] hits;
// ...
public NativeCache(int sz, Class clazz)
{
size = sz;
hits = new int[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;
} else if (isEmpty == 0) {
// если массив заполнен, вытесняем элемент с наименьшим количеством обращений
int min = hits[0];
int index = 0;
for (int i = 1; i < hits.length; i++) {
if (min < hits[i]) {
min = hits[i];
index = i;
}
}
System.out.println(index +" " +slots[index]);
slots[index] = key;
values[index] = 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)){
hits[counter]++;
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("|");
}
}