如何在接口实现中使用泛型构造函数?

8iwquhpp  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(298)

问题可能不太清楚,我会在下面告诉你我想要什么
我有这样一个通用列表界面:

public interface List<Type> {
    void add(Type t);
    Type get(int index);
    void clear();
    Type remove(int index);
}

并用一个例子来实现,因为它太长了:

@Override   
public abstract class DoublyLinkedList<Type> implements List<Type> {
    public void add(Type t) {
        // create new node
        Node<Type> newNode=new Node<>(t, null,null);
        newNode.data = t;
        newNode.previous = tail;
        newNode.next = null;

        // if list is empty
        if (tail == null)
        {
            head = newNode;
        }
        else
        {
            tail.next = newNode;
        }
        tail = newNode;
    }
}

有一个构造器:

public abstract class Node<Type> {

    protected Type data;
    protected Node<Type> next;
    protected Node<Type> previous;

    public Node(Type data, Node<Type> next,Node<Type> previous) {
        this.data = data;
        this.next = next;
        this.previous = previous;

    }

    public Type getData() {
        return data;
    }

    public Node<Type> getNext() {
        return next;
    }
    public Node<Type> getPrevious() {
        return previous;
    }
}

它已经给出了我知道的错误,但我以前看到过类似的东西,在接口实现中使用构造函数:

public interface SortedList<Type extends Comparable<? super Type>>

那么,我能用这个吗,怎么用?

t3irkdon

t3irkdon1#

我能找到的唯一一件事是,您正在绑定创建node的示例,但node是抽象的。只需从节点中删除抽象就可以帮助编译代码。

public class Node<Type> {

    protected Type data;
    protected Node<Type> next;
    protected Node<Type> previous;

    public Node(Type data, Node<Type> next,Node<Type> previous) {
        this.data = data;
        this.next = next;
        this.previous = previous;

    }

    public Type getData() {
        return data;
    }

    public Node<Type> getNext() {
        return next;
    }
    public Node<Type> getPrevious() {
        return previous;
    }
}

相关问题