VL-Programmieren/VL13/Aufgabe02/MyQueue.java

65 lines
1.5 KiB
Java
Raw Normal View History

2024-05-07 18:55:35 +00:00
package VL13.Aufgabe02;
public class MyQueue<T> {
private Object[] myArray;
private int numberOfElements;
private int maxSize;
public MyQueue() {
this.numberOfElements = 0;
this.maxSize = 100;
myArray = new Object[this.maxSize];
}
public void add(T t) {
this.myArray[this.numberOfElements] = t;
this.numberOfElements++;
this.adjustInternalArray();
}
2024-05-07 18:59:14 +00:00
@SuppressWarnings("unchecked")
2024-05-07 18:55:35 +00:00
public T get() {
T retValue = (T) this.myArray[0];
for (int i = 0; i < this.numberOfElements; i++) {
this.myArray[i] = this.myArray[i + 1];
}
this.numberOfElements--;
this.adjustInternalArray();
return retValue;
}
public int size() {
return this.numberOfElements;
}
public int internalSize() {
return this.maxSize;
}
private void adjustInternalArray() {
final int MIN_SIZE = 20;
while (this.numberOfElements <= Math.ceil(this.maxSize * 0.2) && this.maxSize > MIN_SIZE) {
this.maxSize = Math.max(this.maxSize / 2, 20);
Object[] myOldArray = this.myArray;
this.myArray = new Object[this.maxSize];
for (int i = 0; i < this.myArray.length; i++) {
this.myArray[i] = myOldArray[i];
}
}
while (this.numberOfElements >= Math.ceil(this.maxSize * 0.8)) {
this.maxSize = this.maxSize * 2;
Object[] myOldArray = this.myArray;
this.myArray = new Object[this.maxSize];
for (int i = 0; i < myOldArray.length; i++) {
this.myArray[i] = myOldArray[i];
}
}
}
}