Java数组栈peek方法的替代实现方案咨询
解决方案
方案1:提前检查栈状态(推荐,避免依赖异常控制流程)
异常应用于处理意外场景,栈空调用peek是可预见的情况,提前检查top值更高效,也符合代码设计规范。
子方案1a:用Optional<Integer>作为返回类型
这种方式能明确表示“peek可能无返回值”,既保留获取有效值的能力,又能优雅处理空栈场景:
import java.util.Optional; public class Stack { int[] arr; int top = -1; int currSize = 10; // 构造方法及其他方法不变... public Optional<Integer> peek() { if (top == -1) { System.out.println("Stack is empty"); return Optional.empty(); } return Optional.of(arr[top]); } public static void main(String[] args) { Stack st = new Stack(); st.peek(); // 打印空栈提示 st.push(5); // 有值时输出,无值时不执行后续逻辑 st.peek().ifPresent(value -> System.out.println("Top element: " + value)); } }
子方案1b:提前检查+约定标记值
如果坚持用int作为返回类型,可以定义一个语义明确的标记值,替代Integer.MIN_VALUE:
public class Stack { public static final int EMPTY_STACK_FLAG = Integer.MIN_VALUE; int[] arr; int top = -1; int currSize = 10; // 构造方法及其他方法不变... public int peek() { if (top == -1) { System.out.println("Stack is empty"); return EMPTY_STACK_FLAG; } return arr[top]; } public static void main(String[] args) { Stack st = new Stack(); int result = st.peek(); // 打印空栈提示 if (result != EMPTY_STACK_FLAG) { System.out.println(result); } st.push(10); System.out.println(st.peek()); // 输出10 } }
方案2:自定义异常,调用处捕获
自定义空栈异常,让peek在空栈时抛出异常,调用方捕获后打印提示,完全保留peek返回有效值的语义:
步骤1:定义自定义异常
public class EmptyStackException extends RuntimeException { public EmptyStackException(String message) { super(message); } }
步骤2:修改peek方法
public class Stack { int[] arr; int top = -1; int currSize = 10; // 构造方法及其他方法不变... public int peek() { if (top == -1) { throw new EmptyStackException("Stack is empty"); } return arr[top]; } public static void main(String[] args) { Stack st = new Stack(); try { System.out.println(st.peek()); } catch (EmptyStackException e) { System.out.println(e.getMessage()); // 打印空栈提示 } // 控制流正常回到此处,继续执行push st.push(20); try { System.out.println(st.peek()); // 输出20 } catch (EmptyStackException e) { System.out.println(e.getMessage()); } } }
补充说明
不推荐依赖ArrayIndexOutOfBoundsException处理空栈:这种异常属于程序bug类异常,用于标记非法索引访问,而栈空调用peek是业务逻辑中的预期场景,用提前检查或自定义异常更符合Java异常设计原则,代码可读性和可维护性更强。
内容的提问来源于stack exchange,提问作者paneer_curry
相关产品推荐
相关产品推荐

