java基础问题

[code="java"]
List list = new ArrayList();
list.add(new HashMap().put("1", "2"));

    Map map = new HashMap();
    map.put("1", "2");
    list.add(map);

    for (Iterator iterator = list.iterator(); iterator.hasNext();) {
        Map map1 = (Map) iterator.next();
        System.out.println(map1);
    }

[/code]

结果如下:
null
{1=2}

为何不同呢?

下面是HashMap中put(.., ..)方法的实现:
[code="java"]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;
}[/code]

在你的代码中, [code="java"]list.add(new HashMap().put("1", "2")); [/code], 因为[code="java"]new HashMap().put("1", "2")[/code]返回的是null, 所以你的这条语句实际上add的是null.