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

后端 未结 6 931
逝去的感伤
逝去的感伤 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:39

    Because when you print toString(), it will by default print className@HashCode.

    So, when you print array then above will be printed.

    But ArrayList is extened by AbstractCollection class and where the toString() method is overriden as below

     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(' ');
            }
        }
    

    which prints the readable format of the ArrayList object.

提交回复
热议问题