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);
    }
}
阅读 3.7k
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方法

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题