[code="java"]package com.huawei.test;
import java.util.HashMap;
public class HashTest {
public static void main(String[] args) {
getSize1();
getSize2();
}
public static void getSize1(){
HashMap<Object, String> instance = new HashMap<Object, String>();
instance.put(new String(), "xx");
instance.put(new String(), "xx");
System.out.println(instance.size());
}
public static void getSize2(){
HashMap<Object, String> instance = new HashMap<Object, String>();
instance.put(new HashObject(), "xx");
instance.put(new HashObject(), "xx");
System.out.println(instance.size());
}
private static class HashObject{
}
}[/code]
求打印结果是多少____和____?
1,2
两个String是同一对象,它们的hashcode一样
两个HashObject是两个不同对象,没重写hashcode,equals方法没重写
没试验过,先答,第一个答案是1,第二个答案是2.
理由如下:
new String(),这一块应该是内部已经有一致性的判定了。
new HashObject(),这一块由于作者可能没有对一致性判定,所以会采用默认的方式来返回,两个hashObject放进去,肯定是不同的。
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
for (Entry e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
for (Entry e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
好好瞅瞅源码,到底比较的是什么,,两个new出来的String 对象绝对不是同一个对象,它们放在堆里面。String类重写了hashcode,equals方法。