-2
我有以下代码:Java通用类型和等于值是否通过泛型方法返回?
public class SimpleHashMap<K, V> extends AbstractMap<K, V>{
static final int SIZE = 997;
@SuppressWarnings("unchecked")
LinkedList<MapEntry<K, V>>[] buckets =
new LinkedList[SIZE];
public V put(K key, V value)
{
V oldValue = null;
int index = Math.abs(key.hashCode()) % SIZE;
if(buckets[index] == null)
buckets[index] = new LinkedList<MapEntry<K, V>>();
LinkedList<MapEntry<K, V>> bucket = buckets[index];
MapEntry<K, V> pair = new MapEntry<K, V>(key, value);
boolean found = false;
ListIterator<MapEntry<K, V>> iter = bucket.listIterator();
int probes = 0;
while(iter.hasNext())
{
MapEntry<K, V> iPair = iter.next();
probes++;
if(iPair.getKey().equals(key)){
oldValue = iPair.getValue();
iter.set(pair); //zastapienie starego nowym
found = true;
System.out.println("Colision at: " + iPair + " : " + probes + (probes == 1 ? " probe " : " probes ")
+ "needed");
break;
}
}
if(!found)
buckets[index].add(pair);
return oldValue;
}
public V remove(Object o)
{
V removed = null;
if(this.get(o) != null)
{
int index = Math.abs(o.hashCode()) % SIZE;
for(MapEntry<K, V> pair : buckets[index])
{
if(pair.getKey().equals(o))
{
removed = pair.getValue();
buckets[index].remove(buckets[index].indexOf(pair));
break;
}
}
}
return removed;
}
@Override
public Set<java.util.Map.Entry<K, V>> entrySet() {
Set<Map.Entry<K, V>> set = new HashSet<Map.Entry<K, V>>();
for(LinkedList<MapEntry<K, V>> bucket : buckets){
if(bucket == null) continue;
for(MapEntry<K, V> mpair : bucket)
set.add(mpair);
}
return set;
}
}
我interestring在它的方法:
public V remove(Object o)
{
V removed = null;
if(this.get(o) != null)
{
int index = Math.abs(o.hashCode()) % SIZE;
for(MapEntry<K, V> pair : buckets[index])
{
if(pair.getKey().equals(o))
{
removed = pair.getValue();
buckets[index].remove(buckets[index].indexOf(pair));
break;
}
}
}
return removed;
}
当我们以这种方式创建参数化上面的类的实例:
SimpleHashMap<String, String> m =
new SimpleHashMap<String, String>();
add some elements by putAll method...;
为什么我不能做:
if(this.get(o).equals(o))
代替:
if(this.get(o) != null)
我知道errasing上编译级别类型的,但如果上述.equals意味着我们比较两个对象的类型,所以我们比较地址,而不是价值。好的,这是合乎逻辑的。 但我们在此比较:
if(pair.getKey().equals(o))
看起来我们比较两个字符串类型。现在我很困惑,有人可以向我解释在这种情况下这是如何工作的?对不起我的英语不好。我希望有人能帮助我。非常感谢。
MapEntry是自己的类型。它实现了Map.Entry接口。 –
我不明白你的问题或与所有代码的相关性。 –
感谢您的回复。我分析了代码并理解了一切。一切我想知道它与类型错误连接。 –