Created
August 9, 2021 10:38
-
-
Save ozzi-/3c3b7b0becef9027537fc6e6fb86a3f2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Collections; | |
public class RingBuffer<T> { | |
int length; | |
int currentPos = 0; | |
int firstPos = 0; | |
int lastPos; | |
private T[] buffer; | |
@SuppressWarnings("unchecked") | |
public RingBuffer(int length) { | |
this.length = length; | |
this.lastPos = length-1; | |
this.buffer = (T[]) new Object[length]; | |
} | |
public void put(T v) { | |
buffer[currentPos]=v; | |
dumpContent(true,v); | |
currentPos++; | |
flowPos(); | |
} | |
public T pop() { | |
currentPos--; | |
flowPos(); | |
T v = buffer[currentPos]; | |
buffer[currentPos]=null; | |
dumpContent(false,v); | |
return v; | |
} | |
public void flowPos() { | |
if(currentPos<firstPos) { | |
currentPos=lastPos; | |
}else if(currentPos>lastPos) { | |
currentPos=firstPos; | |
} | |
} | |
private void dumpContent(boolean put,T v) { | |
int spaceCount = 0; | |
for (int i = 0; i < buffer.length; i++) { | |
String out = "["+i+"] = "+buffer[i]+", "; | |
if(i<currentPos) { | |
spaceCount+=out.length(); | |
} | |
System.out.print(out); | |
} | |
String action = (put?"PUT":"POP")+"="+v; | |
System.out.println("\r\n"+String.join("", Collections.nCopies(spaceCount, " "))+"/\\ "+action+"\r\n"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment