gpt4 book ai didi

java - 对原始堆栈实现泛型

转载 作者:行者123 更新时间:2023-12-01 17:57:01 26 4
gpt4 key购买 nike

我对如何在java中实现泛型一无所知,所以我希望我能得到一些帮助,将我的堆栈的原始实现(如下)变成一个使用泛型的程序(假设可以只改变一些的事情,而不是如何编写完全不同的程序)。

下面是我的代码:

import java.io.*;
import java.util.*;

public class LinkedListStack {

public static Stack<Integer> stk = new Stack<Integer>();
public static int min, push, top;

public static void main(String[] args) {

//initialize random integer generator
Random rand = new Random();

System.out.println("Stack empty --> top = null, min = null");
stackPush(rand.nextInt(50));

//first value in the stack is the minimum until a smaller integer is pushed
min = stk.peek();

stackPush(rand.nextInt(50));
stackPush(rand.nextInt(50));
stackPop();
stackPush(rand.nextInt(50));
stackPush(rand.nextInt(50));
stackPush(rand.nextInt(50));
stackPush(rand.nextInt(50));
stackPop();
stackPop();
stackPop();
stackPop();
stackPop();
stackPop();
stackPop();

if (!stk.isEmpty()) {
System.out.print("\nFinal stack: ");
for(int x : stk) {
System.out.print(x + " ");
}
} else {
System.out.print("\nStack is empty!");
}

System.out.println();
}

public static int stackPush(int pushInt) {
try {
stk.push(pushInt);
if (stk.peek() < min) {
min = stk.peek();
}
top = stk.peek();
System.out.println("Push " + pushInt + " --> top = " + top + ", min = " + min);

} catch (EmptyStackException e){
System.out.println("ERROR");
}

return pushInt;
}

public static void stackPop() {
try {
stk.pop();
if (stk.peek() < min) {
min = stk.peek();
}
top = stk.peek();
System.out.println("Pop --> top = " + top + ", min = " + min);

} catch (EmptyStackException e) {
System.out.println("Stack already empty!");
}
}
}

最佳答案

首先,您的类不应该是静态的来完成此任务。它也不应该通过公共(public)字段或通过诸如 LinkListStack

之类的命名来公开其底层实现

相反,您可以创建一个类,例如

class MyStack<E> {    
private final Stack<E> wrapped = new Stack<E>();

public void push(E element) {
wrapped.push(e);
}

public E pop() {
return wrapped.pop();
}
}


public class Program {

public static void main(String[] args) {

System.out.println("Stack empty --> top = null, min = null");

MyStack<String> stack = new MyStack<>();

stack.push("hello");

stack.push("world");
}

注意:Java 有一个内置的堆栈,重新发明轮子是一种不好的做法,除非纯粹是为了教育/探索性编程。这个内置堆栈实际上用于提供底层包装值,该值构成了我们实现的支柱。

关于java - 对原始堆栈实现泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43960054/

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