<span style="white-space:pre"></span>Collection collection = new HashSet();
collection.add("lala");
collection.add("haha");
Map map = new HashMap();
map.put("1", "zhagsan");
map.put("2", "lisi");
map.put("3", "wangwu");
map.keySet().addAll(collection);
/*HashMap.values()源码如下,由于HashMap继承自AbstractMap,values,keySet等都已在AbstractMap中定义完成*/
/*public Collection<V> values() {
Collection<V> vs = values;
return (vs != null ? vs : (values = new Values()));
}*/
//AbstractMap.values()函数源码如下:
/*
* public Collection<V> values() {
if (values == null) {
//返回一实现AbstractionCollection的匿名类,该匿名类重写了AbstractCollection.iterator()方法,返回一个Interator类的匿名类,该方法将entrySet().iterator()作为成员变量,最重要的是重写了迭代器的next()方法,用于返回值,即entry.value()
values = new AbstractCollection<V>() {
public Iterator<V> iterator()
{
return new Iterator<V>()
{
private Iterator<Entry<K,V>> i = entrySet().iterator();
public boolean hasNext() {
return i.hasNext();
}
public V next() {
return i.next().getValue();
}
public void remove() {
i.remove();
}
};
}*/
//该条语句会返回UnsupportedOperationException
//AbstractCollection.addAll()源码如下
/*
* public boolean addAll(Collection<? extends E> c) {
boolean modified = false;
for (E e : c)
if (add(e))
modified = true;
return modified;
}*/
//AbstractCollection.add()方法源码如下,由于返回给HashMap.values()方法的AbstractCollection并没有重写add()方法,因此,调用的仍然是AbstractCollection的add()方法,因此抛出异常
/*public boolean add(E e) {
throw new UnsupportedOperationException();
}*/