【问题标题】:Why do these variables have different types in this generic method?为什么这些变量在这个泛型方法中有不同的类型?
【发布时间】:2019-06-23 22:00:33
【问题描述】:

为什么“结果”是用简单的“T”创建的,而“temp”是用“Queue<T>”创建的,有关系吗?

// returns the item at the front of the given queue,
  without 
     // removing it from the queue
     public static <T> T peek(Queue<T> q) 
     throws NoSuchElementException {
        /** COMPLETE THIS METHOD **/
        if (q.isEmpty()) {
            throw new NoSuchElementException("Queue Empty");
        }
        T result = q.dequeue();

        Queue<T> temp = new Queue<T>();
        temp.enqueue(result);

        while(!q.isEmpty()) {
           temp.enqueue(q.dequeue());
        }

        while(!temp.isEmpty()) {
           q.enqueue(temp.dequeue());
        }
        return result;
     }

【问题讨论】:

    标签: java generics queue


    【解决方案1】:

    resulttemp 的类型不同,因为它们代表不同类型的事物。我们来看看这段代码:

    T result = q.dequeue();
    

    在这里,我们存储在result 中的那种东西是当您从队列q 中出列时所返回的任何类型的东西。那么q 存储什么类型的东西呢?查看参数,我们看到qQueue&lt;T&gt;,这意味着队列中的每个元素都是T 类型。因此,我们需要将T 类型赋予result,因为它表示从队列中取出的单个元素。

    另一方面,当我们写作时

    Queue<T> temp = new Queue<T>();
    

    目标是创建一个新的Queue,它可以容纳T 类型的对象。为此,我们需要告诉 Java 我们希望它是 Queue&lt;T&gt;

    这与我们声明result 时不同的原因是我们试图做一些根本不同的事情。 result 旨在容纳单个项目,在这种情况下其类型为 Ttemp 旨在存储项目集合,因此我们将其设为 Queue&lt;T&gt; 以表明它不仅仅是单个 T,而是它们的队列。

    希望这会有所帮助!

    【讨论】:

    • 这更有意义,我不想像看 int 或 float 等那样看 T,谢谢!
    猜你喜欢
    • 2012-12-06
    • 2012-01-15
    • 1970-01-01
    • 2020-12-29
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    相关资源
    最近更新 更多