如何编写一个类实现泛型类?

时间:2017-01-16 03:00:29

标签: java

有一个接口BSTNode可以创建一个特殊的树。

 public interface BSTNode<K extends Comparable<K>, V> {
    /**
     * Recovers the value stored in the node
     * @return the value stored in the node
     */
    public V getValue();

    /**
     * Sets the value stored in the node
     * @param value the value to store in the node
     */
    public void setValue(V value);

    /**
     * Recovers the key stored in the node
     * @return the key stored in the node
     */
    public K getKey();

    /**
     * Sets the key stored in the node
     * @param key the key to store in the node
     */
    public void setKey(K key);  

    /**
     * Recover the parent stored of the current node
     * @return the parent of the current node
     */
    public BSTNode<K, V> getParent();

    /**
     * Set the parent of the current node
     * @param parent to set for the current node
     */
    public void setParent(BSTNode<K, V> parent);
    }

然而,当我实现这个接口时遇到了几个问题:

public abstract class BinarySearchTreeNode implements BSTNode {

    private Object value;
    private Object key;
    private BinarySearchTreeNode parent;
    private BinarySearchTreeNode left;
    private BinarySearchTreeNode right;

    public BinarySearchTreeNode(){
        this.value=null;
        this.key=null;
        this.parent=null;
        this.left=null;
        this.right=null;
    }

    public BinarySearchTreeNode(Object value, Object key, BinarySearchTreeNode parent, BinarySearchTreeNode left, BinarySearchTreeNode right){
        this.value=value;
        this.key=key;
        this.parent=parent;
        this.left=left;
        this.right=right;
    }


    public Object getValue() {
        return this.value;
    }


    public void setValue(Object value) {

    }


    public Comparable getKey() {
        return null;
    }


    public void setKey(Comparable key) {
    }


    public BSTNode<K, V> getParent() {
    }


    public void setParent(BSTNode<K, V> parent);

它不断提醒我V cannot be resolved to a type - K cannot be resolved to a type

有人能告诉我实现这个界面的正确方法吗?

1 个答案:

答案 0 :(得分:1)

是的,在子类中用您自己的类型替换V和K类型参数。有关示例实例,请检查以下代码段。

public interface Transformer<S, T> {
    T transform(S source);

}

public class DocumentToStudentTransformer implements Transformer<Document, BaseStudentDTO> {

    private static final String ID = "_id";
    public static final String STREAM = "stream";
    public static final String GPA = "gpa";
    public static final String AGE = "age";
    public static final String NAME = "name";

    @Override
    public StudentDTO transform(Document source) {
        return new StudentDTO(source.getString(NAME), source.getInteger(AGE), source.getDouble(GPA),
                source.getString(STREAM), ((ObjectId) source.get(ID)).toString());
    }
}

希望这会有所帮助。快乐的编码!