[英]Java Generic types and equals values return by generic methods?
我有以下代码:
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;
}
}
我对它的方法很感兴趣:
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)
我知道在编译级别上擦除类型,但如果高于 .equals 意味着我们比较两个 Object 类型,所以我们比较地址,而不是值。 好吧,这是合乎逻辑的。 但我们在这里比较的是:
if(pair.getKey().equals(o))
看起来我们比较了两种 String 类型。 现在我很困惑,有人可以向我解释这在这种情况下究竟是如何工作的吗? 对不起我的英语不好。 我希望有人能帮我解决这个问题。 非常感谢。
remove(Object o)
的参数是一个键,因此if(pair.getKey().equals(o))
将配对的键与键参数进行比较(将苹果与苹果进行比较),但是this.get(o)
返回一个value ,因此if(this.get(o).equals(o))
将值与键进行比较,这是没有意义的(将苹果与橙子进行比较)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.