【问题标题】:Generic method with stack带堆栈的通用方法
【发布时间】:2019-05-27 08:15:45
【问题描述】:

我的代码:

    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&lt;Integer&gt;
有没有人对此有任何解决方案?
(我希望它与对象一起使用是正确的)

【问题讨论】:

  • 请张贴minimal reproducible example 以准确显示“效果不佳”。
  • public class Stack&lt;E&gt; extends Vector&lt;E&gt; 有一个方法size

标签: java generics stack


【解决方案1】:

如果您出于某种原因真的想使用此算法,那么对于一般的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<>();
    //    ^

【讨论】:

    【解决方案2】:

    如果你想编写(不必要的)方法来查找堆栈中有多少元素,你可以这样做:

    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));
    

    【讨论】:

    • 请注意,您必须在方法的返回类型之前写 ... 只需在答案中查看:private static &lt;T&gt; int findSize(Stack&lt;T&gt; input)。静态关键字不是必需的,但我写了这个,所以它可以在没有Helper helper = new Helper();的情况下调用...
    • 我看到了,我认为这是我的解决方案
    • 如果您觉得这个答案有帮助,您可以考虑接受它和/或投票,以便本网站的其他用户可以从中受益。
    • 返回类型前的实际上是做什么的?
    • 嗯,简而言之,在返回类型之前就是在方法的参数中解析
    猜你喜欢
    • 2021-06-01
    • 2015-07-02
    • 2013-10-13
    • 2016-01-02
    • 1970-01-01
    • 2012-09-18
    • 2017-07-27
    • 2011-07-14
    • 2012-06-30
    相关资源
    最近更新 更多