具有泛型类型的列表接口的队列实现

时间:2019-10-14 13:11:43

标签: java list generics queue type-inference

我需要制作一个队列类,该队列类接受将包含在其中的泛型T。

作为T的容器,我必须使用通用列表。调用Queue的构造函数时,必须指定特定的实现(例如ArrayList或LinkedList)作为参数。

现在,我已将类实现为Queue<T>,构造函数接受了扩展了List<T>的某种类。

这样,我应该可以使用getDeclaredConstructor().newInstance()创建列表的新实例。

import java.lang.reflect.InvocationTargetException;
import java.util.List;

// FIFO QUEUE
public class Queue<T> {
    private List<T> list;

    public Queue(Class<? extends List<T>> aClass) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        list = aClass.getDeclaredConstructor().newInstance();
    }

    public boolean put(T element) {
        return list.add(element);
    }

    public T get() {
        T result = null;
        if (list.size() > 0) {
            result = list.remove(0);
        }
        return result;
    }

    public boolean empty() {
        return list.isEmpty();
    }
}

然后我尝试在主目录中创建一个新的Queue实例:

ArrayList<Integer> arrayList = new ArrayList<>();
Queue<Integer> queue = new Queue<>(arrayList.getClass());

当前我正在使用IntelliJ IDEA,并且无法编译代码。

我遇到一个指向Cannot infer arguments的错误(new Queue<>)。

在维护封装的同时如何正确调用构造函数?

0 个答案:

没有答案