-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLFUCache.java
More file actions
70 lines (61 loc) · 1.66 KB
/
Copy pathLFUCache.java
File metadata and controls
70 lines (61 loc) · 1.66 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
import java.util.ArrayList;
class LFUCache implements Cache {
//structure which represents the cache memory
private ArrayList<Premium> cacheMemory = new ArrayList<>();
private int index;
private int maxNoObjects;
public ArrayList<Premium> getCacheMemory() {
return cacheMemory;
}
public void setMaxNoObjects(int maxNoObjects) {
this.maxNoObjects = maxNoObjects;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public void add(String name, int basicRequest, int premiumRequest) {
if (index == maxNoObjects) {
remove();
index--;
}
index++;
Premium e = new Premium(name, basicRequest, premiumRequest);
e.setNoAppearances(1);
cacheMemory.add(e);
}
//remove the last frequently used element
public void remove() {
int i = 0;
int pos = 0;
//initialize min with the first element's number of appearances
int min = cacheMemory.get(0).getNoAppearances();
for (Premium e : cacheMemory) {
if (e.getNoAppearances() < min) {
min = e.getNoAppearances();
pos = i;
}
i++;
}
//remove the element with min number of appearances (which has index pos)
cacheMemory.remove(pos);
}
public boolean isInCacheMemory(String name) {
for (Premium e : cacheMemory) {
if ((e.getName()).equals(name)) {
return true;
}
}
return false;
}
public Premium getElementCache(String name) {
for (Premium e : cacheMemory) {
if ((e.getName()).equals(name)) {
return e;
}
}
return null;
}
}