问题简述
我去查了下API,发现:
Collection接口里没有toString方法
map.values()返回值是个Collection集合
那么问题来了,这个c1调用的究竟是谁的toString方法?
萌新求助,大神留步,么么哒
Collection<Integer> c1 = map.values();
System.out.println(c1);
源代码
import java.util.Set;
public class Demo044 {
public static void main(String[] args){
//demo01();
//demo02();
Map<String,Integer> map = new HashMap<>();
map.put("z3",23);
map.put("z4",24);
map.put("z5",25);
map.put("z6",26);
Collection<Integer> c1 = map.values();
System.out.println(c1);
}
}
1 回答

慕尼黑的夜晚无繁华
TA贡献1864条经验 获得超6个赞
首先一切类都是Object类的子类
你查看HashMap的源码,values方法,返回的是一个内部类Values对象
public Collection<V> values() {
Collection<V> vs;
return (vs = values) == null ? (values = new Values()) : vs;
}
final class Values extends AbstractCollection<V> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<V> iterator() { return new ValueIterator(); }
public final boolean contains(Object o) { return containsValue(o); }
public final Spliterator<V> spliterator() {
return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super V> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next)
action.accept(e.value);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
这个内部类没有覆盖toString()方法,所以找它的父类AbstractCollection
public String toString() {
Iterator<E> it = iterator();
if (! it.hasNext())
return "[]";
StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
E e = it.next();
sb.append(e == this ? "(this Collection)" : e);
if (! it.hasNext())
return sb.append(']').toString();
sb.append(',').append(' ');
}
}
所以用的是AbstractCollection的toString方法
添加回答
举报
0/150
提交
取消