栈类Stack,包名是java.util.Stack,继承java.util.Vector类。
栈是一种后进先出的数据结构,允许数据的动态插入和删除。
下面是栈类Stack的几个主要用法。
- Stack<Integer> stack = new Stack<>();
- stack.push(1);
- stack.push(2);
- Integer item = stack.pop();
- 输出:2
- Stack<Integer> stack = new Stack<>();
- stack.push(1);
- stack.push(2);
- Integer item = stack.peek();
- 输出:2
- boolean isEmpty = stack.isEmpty();
- 输出:false
- Stack<Integer> stack = new Stack<>();
- stack.push(1);
- stack.push(2);
- int index = stack.search(2);
- 输出:1
- Stack<Integer> stack = new Stack<>();
- stack.push(1);
- stack.push(2);
- Enumeration<Integer> stackEnumeration = stack.elements();
- while (stackEnumeration.hasMoreElements()) {
- Integer element = stackEnumeration.nextElement();
- System.out.println(element);
- }
- 输出:1 2
addElement和push方法非常相似,区别在于新元素被放置的位置。
使用push方法时,新元素位于栈顶;
使用addElement方法时,新元素位于栈底。
- Stack<String> stack = new Stack<>();
- stack.addElement("张三");
- stack.addElement("李四");
- 输出:[张三, 李四]
- stack.removeElement("张三");
- 输出:[李四]
- String element = stack.elementAt(0);
- 输出:李四
注意:java.util.Stack类已经过时,取而代之的是java.util.Deque接口的实现类,例如:ArrayDeque