java - Java 中带有 Map<KeyType, ValueType> 的通用映射

标签 java generics dictionary

我有课,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/

相关文章:

java - Hibernate 如何区分分离对象和 transient 对象,我手动设置 id

java - Wicket 中的 Form<Void> (或一般使用 Void 类型)

python - 将 python 字典转换为变量的最佳方法是什么?

c# - T 实现 Interface<T> 的通用方法

c++ - 更改 STL 映射的赋值

python - 如何将两个字符串转换成单个字典?

java - Android 应用程序的背景图片

java - 将链接列表保存到文件中的单独行中

java - joda时间到sql MS access数据库

c# - 将 DataTable 转换为通用列表?