PR2/Moodle_Uebungen/Generics_Grundlagen/Uebung2.java

135 lines
3.5 KiB
Java
Raw Normal View History

2024-05-07 14:10:06 +02:00
package Generics_Grundlagen;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Uebung2<E> implements Iterable<E> {
private Object[] array;
private int size;
private int capacity;
public Uebung2(int capacity) {
if (capacity <= 0) {
throw new IllegalArgumentException("Capacity must be greater than zero");
}
this.capacity = capacity;
this.array = new Object[capacity];
this.size = 0;
}
public int size() {
return size;
}
public int capacity() {
return capacity;
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == capacity;
}
public void add(E element) {
if (isFull()) {
throw new IllegalStateException("Array is full");
}
array[size++] = element;
}
public E get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index out of bounds");
}
@SuppressWarnings("unchecked")
E element = (E) array[index];
return element;
}
public void remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index out of bounds");
}
// System.arraycopy(array, index + 1, array, index, size - index - 1);
// array[--size] = null;
array[index] = null;
}
public void clear() {
Arrays.fill(array, null);
size = 0;
}
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
private int currentIndex = 0;
@Override
public boolean hasNext() {
//return currentIndex < size -1;
return currentIndex < size;
}
@Override
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
@SuppressWarnings("unchecked")
E element = (E) array[currentIndex];
currentIndex++;
return element;
}
};
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < size; i++) {
sb.append(array[i]);
if (i < size - 1) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
// Test
public static void main(String[] args) {
Uebung2<Integer> array = new Uebung2<>(5);
array.add(1);
array.add(2);
array.add(3);
array.add(4);
array.add(5);
System.out.println("Array: " + array);
System.out.println("Size: " + array.size());
System.out.println("Is Full: " + array.isFull());
try {
array.add(6); // Should throw IllegalStateException
} catch (IllegalStateException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
array.remove(2);
System.out.println("Array after removing element at index 2: " + array);
System.out.println("Size after removal: " + array.size());
System.out.println("Is Empty: " + array.isEmpty());
array.clear();
System.out.println("Array after clearing: " + array);
System.out.println("Size after clearing: " + array.size());
System.out.println("Is Empty after clearing: " + array.isEmpty());
}
}