【问题标题】:Making a small queue (Generics)制作一个小队列(泛型)
【发布时间】:2016-04-09 23:25:10
【问题描述】:

您好,我正在尝试创建一个队列,该队列将重构我的代码以删除 Eclipse 错误消息:“GGCQueue 是原始类型。对泛型类型 GGCQueue 的引用应该被参数化”。我想创建一个永远不会包含超过 10 个元素的队列。我正在尝试遵循“通用”原则来做到这一点,但目前我无法弄清楚如何做到这一点。我有以下代码(在 GGCQueue 类中,构造函数 GGCQueue() 是我需要实现的地方):

import java.util.LinkedList;
import java.util.List;

public class GenericsProblem {

    public static void main(String[] args) {

        GGCQueue ggcQ = new GGCQueue();
        ggcQ.offer(100);
        ggcQ.offer(1000);
        ggcQ.offer(3.33D);
        ggcQ.offer(9);
        ggcQ.offer(7);  
        ggcQ.offer(9.001F);

        System.out.println("polling the queue, expecting 100, got:" + ggcQ.poll());
        System.out.println("polling the queue, expecting 1000, got:" + ggcQ.poll());
        System.out.println("polling the queue, expecting 3.33, got:" + ggcQ.poll());
        System.out.println("polling the queue, expecting 9, got:" + ggcQ.poll());
        System.out.println("polling the queue, expecting 7, got:" + ggcQ.poll());
        System.out.println("polling the queue, expecting 9.001, got:" + ggcQ.poll());

    }

}


class GGCQueue<E> {

    List<E> q = new LinkedList<E>();

    public GGCQueue() {
    //TODO MAKE THE SMALL QUEUE <= 10 ELEMENTS
    }

    public void offer(E element) {
        if (q.size() == 10)
            return;
        q.add(element);
    }

    public E poll() {
        E element = q.remove(0);
        return element;
    }

}

【问题讨论】:

  • 澄清一点,当我运行它时,我希望将结果发送到 SOP(轮询队列,期望 100,得到:100...等等)。感谢您的帮助!

标签: java list generics linked-list queue


【解决方案1】:

看起来像你想要的:

 GGCQueue<Number> ggcQ = new GGCQueue<>();

【讨论】:

  • 对不起,我该怎么办?
  • 错误信息“GGCQueue 是原始类型”。将通过使用GGCQueue&lt;Number&gt; 修复。 Number 是 IntegerDoubleFloat 的超类型。当您提供 100 个时,它会从 int 自动装箱到 Integer,这是一个 Number,因此允许在队列中。投票将返回Number,您的代码将根据需要将其转换为打印“expecting 100, got: 100”的字符串。
  • 非常感谢您的帮助! +1。
猜你喜欢
  • 2021-09-03
  • 2010-12-22
  • 1970-01-01
  • 2015-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-23
  • 2014-04-13
相关资源
最近更新 更多