如何在java中为泛型类创建通用构造函数?

时间:2011-12-30 14:25:05

标签: java generics

我想以通用的方式创建一个KeyValue类,这就是我写的:

public class KeyValue<T,E> 
{

    private T key;
    private E value;
    /**
     * @return the key
     */
    public T getKey() {
        return key;
    }
    /**
     * @param key the key to set
     */
    public void setKey(T key) {
        this.key = key;
    }
    /**
     * @return the value
     */
    public E getValue() {
        return value;
    }
    /**
     * @param value the value to set
     */
    public void setValue(E value) {
        this.value = value;
    }

    public KeyValue <T, E>(T k , E v) // I get compile error here
    {
        setKey(k);
        setValue(v);
    }
}

错误说:“令牌上的语法错误”&gt;“,此令牌后预期的标识符”

我应该如何在java中创建通用构造函数呢?

3 个答案:

答案 0 :(得分:75)

你需要从构造函数的签名中删除<T, E>:它已经隐含了。

public KeyValue(T k , E v) // No compile errors here :)
{
    setKey(k);
    setValue(v);
}

答案 1 :(得分:3)

编写构造函数与编写其他方法的方式完全相同

public KeyValue(T k , E v) 
    {
        setKey(k);
        setValue(v);
    }

答案 2 :(得分:1)

构造函数可以写成

public<T,E> KeyValue(T k,E v){}

但我们也不必写public KeyValue(T k,E v)