Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 用于跟踪N个最新值的适当模式_Java_Design Patterns - Fatal编程技术网

Java 用于跟踪N个最新值的适当模式

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){

我想保存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){
        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个元素。已经为您准备好了一个类