如何在java中围绕Map <k,v =“”>创建泛型类

时间:2015-05-26 05:39:32

标签: java generics dictionary

我是java和java泛型的新手,我想用java的Map创建一个通用的doubleBuffer类

代码是:

import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;
import java.util.Map;
import java.util.HashMap;
class DoubleMap<K, V, M extends Map<K, V>> {
    private ReentrantLock lock = new ReentrantLock();
    private M frontend, backend;

    public DoubleMap() {
        frontend = new M<K, V>();
        backend = new M<K, V>();
    }   

    public void put(K k, V v) {
        lock.lock();
        frontend.put(k, v); 
        lock.unlock();
    }   

    public Map<K, V> getBackend() {
        lock.lock();
        Map<K, V> ret = backend;
        backend = frontend;
        frontend = new M<K, V>();
        lock.unlock();
        return ret;
    }   
}
public class DoubleMapTest implements Runnable {
    static DoubleMap<Integer, Integer, HashMap<Integer, Integer>> map = new DoubleMap<Integer, Integer, HashMap<Integer, Integer>>();
    public void run() {
        Random rand = new Random();
        while (true) {
            map.put(rand.nextInt(), rand.nextInt());
            try {
                Thread.sleep(200);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }   
        }   
    }   

    public static void main(String[] args) {
        DoubleMapTest test = new DoubleMapTest();
        Thread t = new Thread(test);
        t.start();
        while (true) {
            Map<Integer, Integer> toMerge = map.getBackend();
            for (Map.Entry<Integer, Integer> entry : toMerge.entrySet()) {
                System.out.println(entry.getKey() + " = " + entry.getValue());
            }   
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
    }
}

当我编译它时,我收到此错误消息

  

DoubleMapTest.java:10:错误:意外类型           frontend = new M();                          ^ required:找到的类:类型参数M其中M,K,V是类型变量:       M扩展了在DoubleMap类中声明的Map       K扩展了在DoubleMap类中声明的Object       V扩展在DoubleMap类DoubleMapTest.java:11中声明的Object:error:意外类型           backend = new M();                         ^ required:找到的类:类型参数M其中M,K,V是类型变量:       M扩展了在DoubleMap类中声明的Map       K扩展了在DoubleMap类中声明的Object       V扩展在DoubleMap类DoubleMapTest.java:24中声明的Object:error:unexpected type frontend = new M();                        ^ required:找到的类:类型参数M其中M,K,V是类型变量:       M扩展了在DoubleMap类中声明的Map       K扩展了在DoubleMap类中声明的Object       V扩展在类DoubleMap 3错误中声明的Object

1 个答案:

答案 0 :(得分:4)

由于type erasure.,您无法使用new在java中创建泛型类型的实例 这就是你的程序出错的原因。

看一下这篇SO帖子Create instance of generic type in Java?