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

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

    The main difference between an array and an arraylist is that an arraylist is a class that is written in Java and has its own implementation (including the decision to override toString) whereas arrays are part of the language specification itself. In particular, the JLS 10.7 states:

    The members of an array type are all of the following:

    • The public final field length
    • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions.
    • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

    In other words the language specification prevents the toString method of an array to be overriden and it therefore uses the default implementation defined in Object which prints the class name and hashcode.

    Why this decision has been made is a question that should probably be asked to the designers of the language...

提交回复
热议问题