gpt4 book ai didi

java - 有什么替代方法来实现 peek 方法吗?

转载 作者:行者123 更新时间:2023-12-03 07:54:50 25 4
gpt4 key购买 nike

我正在自学数据结构,并一直尝试使用Java来实现它们。目前我正在尝试实现基于数组的堆栈。在堆栈为空时的 peek 方法中,我当前正在捕获 ArrayIndexOutOfBoundsException ,然后返回 Integer.MIN_VALUE 以阻止程序退出并获取它准备进一步的推送操作。是否有任何其他方法可以实现 peek 方法,以便它只打印 catch block 内的消息而不返回 Integer.MIN_VALUE。

public class Stack {
int[] arr;
int top = -1;
int currSize = 10;

/* Constructor */
public Stack() {
arr = new int[10];
}

public void push(int data) {
if (top == arr.length - 1) {
resize();
}
top++;
arr[top] = data;
}

/*
public void pop() {
arr[top] = 0;
top--;
}
*/

public int peek() {
try {
return arr[top];
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Stack is empty");
}
return Integer.MIN_VALUE;
}

/* Resizes the array when space runs out */
public void resize() {
int[] newArr = new int[2 * currSize];
currSize = 2 * currSize;
for (int i = 0; i < newArr.length / 2; i++) {
newArr[i] = arr[i];
}
arr = newArr;
newArr = null;
}

/* Show elements in stack */
public void show() {
for (int i = 0; i <= top; i++) {
System.out.print(arr[i] + " -> ");
}
System.out.println();
}

/* Rturn the no of elements in stack */
public int getSize() {
return top + 1;
}

public static void main(String[] args) {
Stack st = new Stack();
System.out.println(st.peek());
}
}

我尝试省略 Integer.MIN_VALUE return 语句,但程序无法编译。

我期望在打印 catch block 中的消息后,控件将从 peek 方法返回到 main 方法,并且恢复执行主方法中的其他语句(可能是任何推送操作)。

我想到的一个解决方案是我将 peek 方法返回类型更改为 void,打印最上面的值并返回 null 但我不想要选择这条路径是因为我可能想存储返回值并在程序的其他部分使用它。

最佳答案

是的。扔一个Exception 。您可以简单地扔掉您当前正在接住的那个。

public int peek() throws ArrayIndexOutOfBoundsException {
return arr[top];
}

您可以返回 Optional<Integer>喜欢

public Optional<Integer> peek() {
try {
return Optional.of(arr[top]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Stack is empty");
}
return Optional.empty();
}

或者您可以返回 Integer并使其null 。警告,这可能是一个十亿美元的错误1。就像,

public Integer peek() {
try {
return arr[top];
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Stack is empty");
}
return null;
}

1 Null References The Billion Dollar Mistake

关于java - 有什么替代方法来实现 peek 方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76301358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com