为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

开心每一天1111 2019-03-01 10:38:46
问题简述 我去查了下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方法

查看完整回答
反对 回复 2019-03-01
  • 1 回答
  • 0 关注
  • 671 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号