-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCache.java
More file actions
108 lines (85 loc) · 1.87 KB
/
Copy pathCache.java
File metadata and controls
108 lines (85 loc) · 1.87 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
package Leet;
import java.util.HashMap;
import java.util.Map;
class CacheEntry
{
int key;
int value;//unnecessary
long lastAccessed;
}
public class Cache {
int capacity;
int size;
Map<Integer,CacheEntry> cacheEntry;
public Cache(int capacity)
{
this.capacity = capacity;
cacheEntry = new HashMap<Integer, CacheEntry>();
}
public int get(int key) {
if (cacheEntry.containsKey(key))
return key;
return -1;
}
public void put(int key)
{
CacheEntry entry, lruEntry, lruTemp;
int lruKey = 0;
long lru=Long.MAX_VALUE;
entry = cacheEntry.get(key);
//create a new entry in the cache if it the map doesn't have one
if(entry==null)
{
entry = new CacheEntry();
entry.key = key;
entry.value = 1;
//System.out.println("If:::"+"key::"+entry.key+" value::"+entry.value);
size++;
}
//if it exists, increment the value
else
{
entry.value++;
}
//update timestamp
entry.lastAccessed = System.nanoTime();
//if not at MAX, then add to map
if(this.size <= this.capacity)
cacheEntry.put(key, entry);
//if maxed out
else
{
//get least accessed time
for(Map.Entry<Integer, CacheEntry> i : cacheEntry.entrySet())
{
lruTemp= i.getValue();
if(lruTemp.lastAccessed<lru)
{
lru = lruTemp.lastAccessed;
lruEntry = lruTemp;
lruKey = lruTemp.key;
}
}
cacheEntry.remove(lruKey);
// entry = new CacheEntry();
// entry.key = key;
// entry.value = 1;
// entry.lastAccessed = System.nanoTime();
cacheEntry.put(key, entry);
size++;
}
}
public static void main(String[] args) {
Cache cache = new Cache(4);
cache.put(1);
cache.put(2);
cache.put(3);
cache.put(1);
cache.put(4);
cache.put(5);
for(Map.Entry<Integer, CacheEntry> j : cache.cacheEntry.entrySet())
{
System.out.println(j.getKey());
}
}
}