我有课,TestMap
, 只有静态方法(包括 main
)用于测试 Maps
.类中有一个方法,例如,它接受一个映射,键和值的类型表示为KeyType
。和 ValueType
分别如下图;
public static <KeyType,ValueType> void printMap( String msg, Map<KeyType,ValueType> m )
{
System.out.println( msg + ":" );
Set<Map.Entry<KeyType,ValueType>> entries = m.entrySet( );
for( Map.Entry<KeyType,ValueType> thisPair : entries )
{
System.out.print( thisPair.getKey( ) + ": " );
System.out.println( thisPair.getValue( ) );
}
}
我的问题是,如果我想重写这个类以便它可以实例化,而不是只包含静态方法,我如何在类中定义一个可以与 Map<KeyType, ValueType>
一起使用的映射? ?
我试过如下定义一个 map ,但它似乎不起作用。
private Map<KeyType, ValueType> internalMap;
有什么想法吗?
根据第一条评论,我尝试添加到类定义中,然后按如下方式设置构造函数;
public class TestMap<KeyType, ValueType>
{
private Map<KeyType, ValueType> internalMap;
/*
* Constructor which accepts a generic Map for testing
*/
public <KeyType,ValueType> TestMap(Map<KeyType, ValueType> m)
{
this.internalMap = m;
}
}
但是,构造函数中的赋值会抛出一个错误,指出它是类型不匹配,并且无法从 java.util.Map 转换为 java.util.Map
最佳答案
你的意思是:
class MyMap<KeyType, ValueType> {
private Map<KeyType, ValueType> internalMap;
}
编辑:构造函数中不需要类型参数:
class TestMap<KeyType, ValueType>
{
private Map<KeyType, ValueType> internalMap;
/*
* Constructor which accepts a generic Map for testing
*/
public TestMap(Map<KeyType, ValueType> m)
{
this.internalMap = m;
}
}
关于java - Java 中带有 Map<KeyType, ValueType> 的通用映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12771196/