Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package liu_apCompSci;
- import java.util.Arrays;
- public class RingBuffer {
- // instance variables
- private char[] characters;
- private int front;
- private int rear;
- // constructor
- public RingBuffer(int capacity) {
- characters = new char[capacity + 1];
- front = 0;
- rear = 0;
- }
- // makes the front equal to rear without destroying any values in the middle
- public void flush() {
- front = rear;
- }
- public boolean add(char ch) {
- // check if it's full
- if (rear - front == (characters.length - 1) || front - rear == 1) {
- return false;
- } else {
- // insert the value into the rear location
- characters[rear] = ch;
- // increment rear
- if (rear != characters.length - 1) {
- rear++;
- } else {
- // if it goes over the length of the array
- rear = 0;
- }
- return true;
- }
- }
- // check if front equals rear, thereby making it empty
- public boolean isEmpty() {
- return front == rear;
- }
- public char remove() {
- // check if it's full
- if (rear - front == (characters.length - 1) || front - rear == 1) {
- return ' ';
- } else {
- // increment the front
- if (front != characters.length - 1) {
- front++;
- // return the value that was last there
- return characters[front - 1];
- } else {
- // if it leaks over the length of the array
- front = 0;
- return characters[characters.length - 1];
- }
- }
- }
- public char peek() {
- // check if it's empty
- if (front == rear) {
- return '!';
- } else {
- // look at the top value of the "queue"
- return characters[front];
- }
- }
- // accessor method
- public int getFront() {
- return front;
- }
- // accessor method
- public int getRear() {
- return rear;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement