定义一个泛型类MyStack,实现栈的基本操作:push、pop、peek、isEmpty。 定义一个泛型类MyQueue,实现队列的基本操作:add、remove、peek、isEmpty。 定义一个泛型类MyArrayList,实现数组列表的基本操作:add、remove、get、size。
时间: 2023-07-10 17:17:03 浏览: 87
泛型编程小实例(以List为例)
好的,我来为您解答这个问题。
下面是MyStack类的代码实现:
```java
public class MyStack<T> {
private List<T> stack;
public MyStack() {
stack = new ArrayList<>();
}
public void push(T element) {
stack.add(element);
}
public T pop() {
if (isEmpty()) {
throw new EmptyStackException();
}
return stack.remove(stack.size() - 1);
}
public T peek() {
if (isEmpty()) {
throw new EmptyStackException();
}
return stack.get(stack.size() - 1);
}
public boolean isEmpty() {
return stack.isEmpty();
}
}
```
下面是MyQueue类的代码实现:
```java
public class MyQueue<T> {
private List<T> queue;
public MyQueue() {
queue = new ArrayList<>();
}
public void add(T element) {
queue.add(element);
}
public T remove() {
if (isEmpty()) {
throw new NoSuchElementException();
}
return queue.remove(0);
}
public T peek() {
if (isEmpty()) {
throw new NoSuchElementException();
}
return queue.get(0);
}
public boolean isEmpty() {
return queue.isEmpty();
}
}
```
下面是MyArrayList类的代码实现:
```java
public class MyArrayList<T> {
private T[] array;
private int size;
public MyArrayList() {
array = (T[]) new Object[10];
size = 0;
}
public void add(T element) {
if (size == array.length) {
T[] newArray = (T[]) new Object[array.length * 2];
System.arraycopy(array, 0, newArray, 0, array.length);
array = newArray;
}
array[size++] = element;
}
public T remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
T removed = array[index];
System.arraycopy(array, index + 1, array, index, size - index - 1);
array[--size] = null;
return removed;
}
public T get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
return array[index];
}
public int size() {
return size;
}
}
```
希望我的回答能够帮助到您!
阅读全文