Java byte数组实现LRU算法。
import java.util.Random;
public class LRUTestCase {
public static void main(String[] args) {
int addIndex = 7;
for(int i=0;i<addIndex;i++) {
addLRUItem();
}
showBytes(lruList);
}
private static final byte[] nums = {-1,-2,-3,-4,-5,-6,-7,-8,-9};
private static final int total = 4;
private static final byte[] lruList = new byte[total];
private static void addLRUItem() {
//1.从nums获取随机数 item
byte item = nums[new Random().nextInt(nums.length)];
System.out.println("item: "+((byte)item));
byte[] tmp = new byte[total];
System.arraycopy(lruList, 0, tmp, 0, total);
lruList[0] = item;
int start = 1;
int tmpIndex = start - 1;
for(int lruIndex = start ;lruIndex<total;lruIndex++) {
while(item == tmp[tmpIndex]) {
tmpIndex += 1;//1为插入个数
}
lruList[lruIndex] = tmp[tmpIndex];
tmpIndex++;
}
}
private static void showBytes(byte[] bytes) {
for(byte item: bytes) {
System.out.println(item);
}
}
}