java堆栈如何使用
堆栈的基本概念
堆栈(Stack)是一种遵循后进先出(LIFO)原则的数据结构,核心操作包括压栈(push)和弹栈(pop)。Java中可通过java.util.Stack类或Deque接口实现。
使用java.util.Stack类
Stack是Java标准库提供的类,继承自Vector,但推荐优先使用Deque实现(见下文)。
初始化堆栈
Stack<Integer> stack = new Stack<>();
压栈操作
stack.push(1); // 元素1入栈
stack.push(2); // 元素2入栈
弹栈操作

int topElement = stack.pop(); // 弹出栈顶元素2
查看栈顶元素
int peekElement = stack.peek(); // 获取栈顶元素1但不移除
检查堆栈是否为空
boolean isEmpty = stack.empty();
使用Deque接口(推荐)
Java官方推荐用ArrayDeque替代Stack,因其性能更好且避免了Vector的同步开销。

初始化堆栈
Deque<Integer> stack = new ArrayDeque<>();
压栈与弹栈
stack.push(1); // 入栈
stack.push(2);
int top = stack.pop(); // 出栈
其他操作
int peek = stack.peek(); // 查看栈顶
boolean isEmpty = stack.isEmpty();
堆栈的典型应用场景
- 括号匹配:检查表达式中的括号是否成对出现。
- 函数调用栈:JVM用堆栈管理方法调用和返回地址。
- 逆波兰表达式:通过堆栈计算后缀表达式。
示例:括号匹配校验
public boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else {
if (stack.isEmpty()) return false;
char top = stack.pop();
if ((c == ')' && top != '(') ||
(c == ']' && top != '[') ||
(c == '}' && top != '{')) {
return false;
}
}
}
return stack.isEmpty();
}
注意事项
- 线程安全:
Stack是线程安全的(继承自Vector),但性能较低;ArrayDeque非线程安全。 - 容量限制:
ArrayDeque默认初始容量为16,动态扩容,适合高频操作。 - 替代方案:复杂场景可考虑
LinkedList实现Deque,但通常ArrayDeque更高效。






