Vorlesung 13 / Aufgabe 2
This commit is contained in:
parent
f6a3b314cb
commit
8a7d98881e
23
VL13/Aufgabe02/Aufgabe02.java
Normal file
23
VL13/Aufgabe02/Aufgabe02.java
Normal file
@ -0,0 +1,23 @@
|
||||
package VL13.Aufgabe02;
|
||||
|
||||
public class Aufgabe02 {
|
||||
public static void main(String[] args) {
|
||||
MyQueue<Integer> integerQueue = new MyQueue<Integer>();
|
||||
|
||||
// fill the queue with some values.
|
||||
System.out.printf("\n%s:\n", "Aufbau der Queue");
|
||||
|
||||
for (int i = 0; i < 150; i++) {
|
||||
integerQueue.add(i);
|
||||
System.out.printf("Elemente: %d - Größe: %d\n", integerQueue.size(), integerQueue.internalSize());
|
||||
}
|
||||
|
||||
// clear the queue to check the resizing of the internal storage.
|
||||
System.out.printf("\n%s:\n", "Abbau der Queue");
|
||||
|
||||
while (integerQueue.size() > 0) {
|
||||
integerQueue.get();
|
||||
System.out.printf("Elemente: %d - Größe: %d\n", integerQueue.size(), integerQueue.internalSize());
|
||||
}
|
||||
}
|
||||
}
|
63
VL13/Aufgabe02/MyQueue.java
Normal file
63
VL13/Aufgabe02/MyQueue.java
Normal file
@ -0,0 +1,63 @@
|
||||
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();
|
||||
}
|
||||
|
||||
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];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user