Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
906 views
in Technique[技术] by (71.8m points)

how to create a generic constructor for a generic class in java?

I want to create a KeyValue class but in generic manner and this is what I've written:

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);
    }
}

the error says : "Syntax error on token ">", Identifier expected after this token"

how should I create a generic constructor in java then?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to remove <T, E> from the constructor's signature: it's already there implicitly.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...