簡體   English   中英

帶堆棧的通用方法

[英]Generic method with stack

我的代碼:

    public static void spilledOn (Stack<Object> st1,Stack<Object> st2){
    while (!st2.isEmpty()){
            st1.push(st2.pop());
    }    
}

public static int findLengthInStack (Stack<Object> st1){
    Stack<Object> tmp=new Stack<>();
    int count=0;
    while (tmp.isEmpty()){
        tmp.push(st1.pop());
        count++;
    }
    toolsForAnything.spilledOn(st1, tmp);
    return count;
}

當我調用此方法並且使用另一種類型的堆棧時,它不能很好地工作(我的意思是我使用Stack<Integer>
有人對此有任何解決方案嗎?
(我希望它與對象一起使用是正確的)

如果要編寫(不必要的)方法來查找堆棧中有多少個元素,可以這樣進行:

public class Helper {

    private static <T> int findSize(Stack<T> input) {
        return input.size();
    }

    public static void main(String[] args) {

        Stack<Integer> stack = new Stack<>();
        stack.push(4);
        stack.push(9);

        System.out.println(findSize(stack));

    }
}

為什么我說不必要 因為您可以簡單地寫:

System.out.println(stack.size());

代替:

System.out.println(findSize(stack));

如果您確實出於某種原因想要使用此算法,那么對於通用Stack您需要為每個方法聲明一個類型參數。

// (Really an API would be using super and extends here,
//   but let's keep it simple.)
public static <T> void spilledOn (Stack<T> st1,Stack<T> st2){
    //        ^^^                       ^            ^
[...]
// (I'm using a different name (E vs T) here
//     just to illustrate that I am declaring two variables.
//   Using the same letter would be more conventional.)
public static <E> int findLengthInStack (Stack<E> st1){
    //        ^^^                              ^
    Stack<E> tmp=new Stack<>();
    //    ^

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM