如何在java中为泛型类创建泛型构造函数? [英] how to create a generic constructor for a generic class in java?
本文介绍了如何在java中为泛型类创建泛型构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个KeyValue类,但采用通用方式,这就是我写的:
public class KeyValue< ; T,E - 代替;
{
private T key;
私人E值;
/ **
* @返回键
* /
public T getKey(){
return key;
}
/ **
* @param键设置
* /
的密钥public void setKey(T key){
this.key =键;
}
/ **
* @返回值
* /
public E getValue(){
返回值;
}
/ **
* @param value设置的值
* /
public void setValue(E value){
this.value =值;
}
public KeyValue< T,E>(T k,E v)//我在这里得到编译错误
{
setKey(k);
setValue(v);
错误表示:令牌上的语法错误> ,标识符应该在此标记之后
我应该如何在java中创建一个通用构造函数?
解决方案 您需要从构造函数的签名中移除< T,E>
:它已经隐含在那里。
public KeyValue(T k,E v)//这里没有编译错误:)
{
setKey(k);
setValue(v);
}
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?
解决方案 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);
}
这篇关于如何在java中为泛型类创建泛型构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文