Created
June 5, 2018 10:38
-
-
Save Apondi/d414f54732573400d1894125e8593c4a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* | |
* To change this license header, choose License Headers in Project Properties. | |
* To change this template file, choose Tools | Templates | |
* and open the template in the editor. | |
*/ | |
package queue; | |
import java.util.Arrays; | |
/** | |
* | |
* @author User | |
* @param <T> | |
*/ | |
public class Queue<T> implements QueueInterface { | |
private T[] queueLine; | |
private final int maxSize = 10; | |
//queue pointers | |
private int queueStart = 0; | |
private int queueEnd = 0; | |
//queue management | |
private int totalEnqueued = 0; | |
private int totalDeququed = 0; | |
public Queue() { | |
this.queueLine = (T[]) new Object[maxSize]; | |
} | |
// /** | |
// * @param args the command line arguments | |
// */ | |
// public static void main(String[] args) { | |
// // TODO code application logic here | |
// } | |
@Override | |
public void enqueue(Object o) { | |
if(!isFull()){ | |
if(queueEnd <= queueLine.length){ | |
//add element to the position of the questartValue | |
//add the queueStart value by 1 | |
this.queueLine[queueEnd] = (T) o; | |
this.queueEnd++; | |
} else if(queueEnd > queueLine.length) { | |
this.queueStart = 0; | |
this.queueLine[queueEnd] = (T) o; | |
this.queueEnd++; | |
} | |
} else { //the queue is full | |
expand(); | |
enqueue(o); | |
} | |
this.totalEnqueued++; | |
} | |
@Override | |
public void dequeue() { | |
//remove the first element in the queue | |
queueLine[this.queueStart] = null; | |
if (queueStart <= queueLine.length){ | |
this.queueStart++; | |
} else { | |
this.queueStart = 0; | |
} | |
} | |
@Override | |
public void clear() { | |
Arrays.fill(queueLine, null); | |
} | |
@Override | |
public boolean contains(Object o) { | |
for(int i = 0; i<=queueLine.length; i++){ | |
if(queueLine[i] == o){ | |
return true; | |
} | |
} | |
return false; | |
} | |
@Override | |
public Object Peek() { | |
return queueLine[this.queueStart]; | |
} | |
@Override | |
public boolean empty() { | |
return false; | |
} | |
@Override | |
public boolean isFull() { | |
return queueStart == queueEnd; | |
} | |
private void expand() { | |
//create a new array with double the size | |
T[] tempQueue = (T[]) new Object[maxSize * 2]; | |
//copy the old array to the new array | |
System.arraycopy( queueLine, this.queueEnd, tempQueue, this.queueEnd, (queueLine.length-queueEnd) ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment