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

查看:413
本文介绍了java - 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);
    }
}

解决方案

首先一切类都是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方法

这篇关于java - Collection接口没有toString方法,那这个输出调用的到底是谁的toString方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆