I want to save 5 most recent int
values. Code below uses int[] savedValues
and current index counter store values.
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];
}
}
What would be a cleaner way to keep track of most recent values?
Aucun commentaire:
Enregistrer un commentaire