I want to create a KeyValue class but in generic manner and this is what I've written:
我想创建一个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);
}
}
the error says : "Syntax error on token ">", Identifier expected after this token"
错误是:“在令牌“>”上的语法错误,该令牌后面预期的标识符”
how should I create a generic constructor in java then?
那么,我应该如何在java中创建泛型构造函数呢?
3 个解决方案
#1
72
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);
}
#2
3
Write constructor exactly the same way you wrote other methods
编写构造函数的方式与编写其他方法的方式完全相同
public KeyValue(T k , E v)
{
setKey(k);
setValue(v);
}
#3
0
the constructor can be written as
构造函数可以写成
public<T,E> KeyValue(T k,E v){}
but its not necessary also we can writepublic KeyValue(T k,E v)
但也没有必要我们可以写公钥值(tk,E v)
#1
72
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);
}
#2
3
Write constructor exactly the same way you wrote other methods
编写构造函数的方式与编写其他方法的方式完全相同
public KeyValue(T k , E v)
{
setKey(k);
setValue(v);
}
#3
0
the constructor can be written as
构造函数可以写成
public<T,E> KeyValue(T k,E v){}
but its not necessary also we can writepublic KeyValue(T k,E v)
但也没有必要我们可以写公钥值(tk,E v)