Java 用于跟踪N个最新值的适当模式
我想保存5个最新的Java 用于跟踪N个最新值的适当模式,java,design-patterns,Java,Design Patterns,我想保存5个最新的int值。下面的代码使用int[]savedValue和当前索引计数器存储值 public class MyBuffer { private final int BUFFER_SIZE = 5; int[] savedValues = new int[BUFFER_SIZE]; int index = 0; boolean isInitialCycle = true; public void save(int value){
int
值。下面的代码使用int[]savedValue
和当前索引计数器存储值
public class MyBuffer {
private final int BUFFER_SIZE = 5;
int[] savedValues = new int[BUFFER_SIZE];
int index = 0;
boolean isInitialCycle = true;
public void save(int value){
savedValues[index] = value;
index++;
if(index == BUFFER_SIZE){
index = 0;
isInitialCycle = false;
}
}
public Integer restore(int stepsBack){
if(( isInitialCycle && stepsBack > index ) || stepsBack > BUFFER_SIZE){
return null;
}
int recordIndex = ( BUFFER_SIZE + index - stepsBack ) % BUFFER_SIZE;
return savedValues[recordIndex];
}
}
跟踪最新值的更干净的方法是什么?您可以使用java中内置的LinkedList类
LinkedList<Integer> queue = new LinkedList<>();
queue.add(1);
queue.add(2);
Integer mostRecent = queue.getLast()//Gives most recent element
Integer leastRecent = queue.geFirst()//Gives least recent element
//To add new element if the buffer reaches
queue.removeFirst();
queue.add(3);
LinkedList队列=新建LinkedList();
添加(1);
添加(2);
整数mostRecent=queue.getLast()//给出最近的元素
整数leastRecent=queue.geFirst()//给出最近的元素最少
//如果缓冲区到达,则添加新元素
queue.removeFirst();
添加(3);
使用列表。如果已达到最大尺寸,请移除最后一个图元,并将新图元添加到前面。要恢复,只需从列表中获取第n个元素。已经为您准备好了一个类