Why toString() method works differently between Array and ArrayList object in Java

后端 未结 6 913
逝去的感伤
逝去的感伤 2020-12-14 04:08
    String[] array = {\"a\",\"c\",\"b\"};
    ArrayList list = new ArrayList();
    list.add(\"a\");
    list.add(\"b\");
    list.add(\"         


        
6条回答
  •  时光说笑
    2020-12-14 04:35

    This is the toString method call for ArrayList. But for Arrays you cant find such.

     /**
     * 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
     * ("[]").  Adjacent elements are separated by the characters
     * ", " (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 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(' ');
        }
    }
    

提交回复
热议问题