编写测试代码,测试所实现的三个数据结构的基本操作是否正确。
时间: 2024-02-19 13:57:31 浏览: 65
好的,下面是测试代码:
```java
public class Test {
public static void main(String[] args) {
testMyStack();
testMyQueue();
testMyArrayList();
}
private static void testMyStack() {
MyStack<Integer> stack = new MyStack<>();
stack.push(1);
stack.push(2);
stack.push(3);
assert !stack.isEmpty();
assert stack.peek() == 3;
assert stack.pop() == 3;
assert stack.pop() == 2;
assert stack.pop() == 1;
assert stack.isEmpty();
}
private static void testMyQueue() {
MyQueue<Integer> queue = new MyQueue<>();
queue.add(1);
queue.add(2);
queue.add(3);
assert !queue.isEmpty();
assert queue.peek() == 1;
assert queue.remove() == 1;
assert queue.remove() == 2;
assert queue.remove() == 3;
assert queue.isEmpty();
}
private static void testMyArrayList() {
MyArrayList<Integer> list = new MyArrayList<>();
for (int i = 1; i <= 10; i++) {
list.add(i);
}
assert list.size() == 10;
assert list.get(0) == 1;
assert list.get(9) == 10;
assert list.remove(9) == 10;
assert list.size() == 9;
assert list.get(8) == 9;
}
}
```
测试代码中,我对MyStack、MyQueue、MyArrayList三个类进行了基本操作的测试,包括入栈/队列、出栈/队列、查看栈顶/队首元素、判断是否为空、添加元素、删除元素、获取元素等操作。如果测试中断言失败,会抛出AssertionError异常。如果测试代码没有抛出异常,那么说明测试通过,三个数据结构的基本操作实现正确。
阅读全文