猿问

Collection接口没有toString方法,那这个输出调用的到底是谁的toString方法呢?

问题简述

我去查了下API,发现:

  1. Collection接口里没有toString方法
  2. 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);
    }
}
开心每一天1111
浏览 672回答 1
1回答

慕尼黑的夜晚无繁华

首先一切类都是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方法
随时随地看视频慕课网APP

相关分类

Java
我要回答