0
点赞
收藏
分享

微信扫一扫

为什么打印ArrayList对象输出的是内容?

吃面多放酱 2022-03-11 阅读 72

查看源码即可

1. 第一步

点击ArrayList查看源码,发现其中并没有toString()方法,查看他的父类

2. 第二步

在父类AbstractList中查找,依然没有,在查看上一层父类

3. 第三步

在AbstractList的父类AbstractCollection查找,发现重写

/**
     * Returns a string representation of this collection.  The string
     * representation consists of a list of the collection's elements in the
     * order they are returned by its iterator, enclosed in square brackets
     * (<tt>"[]"</tt>).  Adjacent elements are separated by the characters
     * <tt>", "</tt> (comma and space).  Elements are converted to strings as
     * by {@link String#valueOf(Object)}.
     *
     * @return a string representation of this collection
     */
    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(' ');
        }
    }
举报

相关推荐

0 条评论