当我尝试从main
类访问泛型方法时,它会给我一个错误。
当我执行以下操作时:
Integer key = map.remove(15);
然后Eclipse说“类型remove(String)
中的方法IMiniMap<String,Integer>
不适用于参数(int)
”访问泛型类型方法的方法是什么? / p>
public class Tester {
public static void main(String[] args)
{
IMiniMap<String,Integer> map = new SimpleListMM<String,Integer>();
map.put("B",15);
map.put("A",5);
map.put("R",-5);
map.put("D",55);
map.put("Poems",128);
map.put("Plays",256);
// System.out.println(map.size());
// map.put("B", 22);
// System.out.println(map.keys());
//System.out.println(map.toString());
Integer key = map.remove(15);
}
}
public abstract class AbstractListMM<K,V> implements IMiniMap<K,V>{
protected List <K> keys;
protected List <V> vals;
// Initialize the lists of keys and values with a concrete instance
public AbstractListMM()
{
this.keys = new ArrayList<K>();
this.vals = new ArrayList<V>();
}
public AbstractListMM(List <K> keys, List <V> vals)
{
this.keys = keys;
this.vals = vals;
}
// Return the number of bindings based on the size of the key list
public int size()
{
return keys.size();
}
// Based on the lists size
public boolean isEmpty()
{
return (keys.isEmpty() && vals.isEmpty());
}
// Make a (shallow) copy of the keys list and return it
public List<K> keys()
{
List<K> newKeys = this.keys;
return newKeys;
}
// Make a (shallow) copy of the vals list and return it
public List<V> values()
{
List<V> vals = this.vals;
return vals;
}
// Use this.indexOf() to locate the given key as quickly as possible
public boolean contains(K key)
{
int pos = this.indexOf(key);
if(pos < 0)
return false;
else
return true;
/*if(this.indexOf(key) < 0)
return false;
else
return true;*/
}
// Use this.indexOf() to determine if a given key is present and
// return its associated value; return null if the key is not
// present
//
// TARGET COMPLEXITY: Same speed as indexOf()
public V get(K key)
{
int pos = this.indexOf(key);
if(pos < 0)
return null;
else
return vals.get(pos);
}
// Use this.indexOf() to determine the location of the given
// key/value and remove it from the corresponding lists
//
// TARGET COMPLEXITY: O(N) due to list elements shifting
public V remove(K key)
{
int pos = this.indexOf(key);
if(pos < 0)
return null;
else
return vals.remove(pos);
}
// Find the numeric index of the key as quickly as possible based on
// the type of ListMM being implemented. Return a negative number if
// the given key is not present.
public abstract int indexOf(K key);
// Associate the given key with the given value in the
// lists. Creates an ordering of keys that is compatible with how
// indexOf() works to locate keys.
public abstract V put(K key, V value);
}
答案 0 :(得分:1)
您已指定K类型
AbstractListMM<K,V> implements IMiniMap<K,V>
将是一个类型字符串,它来自这里:
IMiniMap<String,Integer> map = new SimpleListMM<String,Integer>();
因此,您需要提供删除方法remove(K key)
作为字符串而不是整数
map.remove("B");