适当的模式来跟踪N个最近的值

时间:2017-11-03 07:33:52

标签: java design-patterns

我想保存5个最近的int值。下面的代码使用int[] savedValues和当前索引计数器存储值。

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];
    }    
}

如何更清晰地跟踪最新值?

1 个答案:

答案 0 :(得分:1)

您可以使用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);