为什么通用地图不起作用?

时间:2017-05-24 00:12:10

标签: java generics

class MyMap<K,V> {

   private Map<K,V> map = new HashMap<K,V>();
   ...

   public void add(K key, V value){
      map.put(key,value);
   }

   private load(String filePath){
      ...
      while(true){
        ...
        People key = new People();
        Information info = new Information();
        ...
       this.add(key, info);
     }
   }
}

它抱怨说:

add(K,V) is not applicable for the arguments "[People, Information]".

2 个答案:

答案 0 :(得分:0)

练习这门课的正确方法:

public class Main {

    public static void main(String[] args){
        MyMap<People, Information> map = new MyMap<>();
        People p = new People();
        Information i = new Information();
        map.add(p, i);
    }
}

答案 1 :(得分:0)

你试图直接将值插入Hash映射而不指定它会给编译时错误的通用