队列<e>接口的实现</e>

时间:2014-04-29 07:53:03

标签: java arrays generics interface

我无法理解泛型,接口和数组的细微差别以及如何将它们结合使用。我有一个中级Java类的作业。作业如下:

  • 创建实现Queue的通用类SimpleQueue
  • 使用构造函数初始化具有5个插槽的数组。
  • 不允许使用ArrayList
  • 如果数组填满,我们必须能够增加数组的大小

我遇到的问题是数组的初始化。这是我的代码:

import java.util.Collection;
import java.util.Iterator;
import java.util.Queue;

public class SimpleQueue<E> implements Queue<E>{

    private E myQueue[];

    //Constructor with no arguments.
    public SimpleQueue() {
        myQueue = new [5];
        System.out.println("A queue with length " + myQueue.length + " was created.");
    }
}
Eclipse抱怨说我们无法创建通用数组。我已经设法通过这样做来实现它:

private Object myQueue[] = Object[5];

...但我觉得这会破坏使用泛型的目的。我是否误解了仿制药的使用?指针将不胜感激!

这是我用来测试我的泛型类的代码:

public class SimpleQueueTester {

    public static void main(String [] args) {
        SimpleQueue<String> myStringQueue = new SimpleQueue<>();
        SimpleQueue<Integer> myIntegerQueue = new SimpleQueue<>();
    }
}

免责声明:请不要认为我想为我做完作业。我只是坚持这一点,我认为这将是最好的问题。谢谢!

修改:我提出了一些建议,现在我的代码如下:

public class SimpleQueue<E> implements Queue<E>{

    private E[] myQueue;

    @SuppressWarnings("unchecked")
    //Constructor with no arguments.
    public SimpleQueue() {

        //This was changed. What does (E[]) do exactly?            
        this.myQueue = (E[]) new Object[5];
        System.out.println("A queue with length " + this.myQueue.length + " was created.");
    }
}

谢谢你的建议!你们真棒。

3 个答案:

答案 0 :(得分:2)

您可以创建一个Object数组Object[] myQueue;,并在需要获取值时将其内容强制转换为E

以下是一个例子:

public class MyQueue<E> implements Queue<E> {
    private Object[] elements;
    private int startOfQueueIndex;
    private int numberOfElements;

    public MyQueue(int initialCapacity) {
        elements = new Object[initialCapacity);
        startOfQueueIndex = 0;
        numberOfElements = 0;
    }

    public boolean add(E e) {
        if (numberOfElements == elements.length)
            increaseElementArraySize();

        elements[(startOfQueueIndex + numberOfElements++) % elements.length] = e;
    }

    public E remove() {
        if (numberOfElements == 0)
            throw new NoSuchElementException();

        E element = (E)elements[startOfQueueIndex];

        startOfQueueIndex = (startOfQueueIndex + 1) % elements.length;

        return element;
    }

    // The rest of the methods go here ...
}

答案 1 :(得分:1)

要获得学习参考,您可能需要查看LinkedList界面Queue<E>的影响方式:这里是grepcode link的openjdk实现。

LinkedList没有底层数组,而是使用Node个对象。这样可以在将新对象添加到列表时轻松分配新对象。

有关如何处理基础数组(确保足够的空间等)的参考,您可能希望看到ArrayList

代码评论很好,我希望它可以帮到你。

答案 2 :(得分:0)

您无法创建新的E实例或E数组,因为E在编译时是未知类型。但你可以创建一个E列表。

private java.util.List<E> myQueue;

是正确的方法。

相关问题