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

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

    The short answer is because toString is defined in a few different places, with different behaviours.

    The Arrays class defines toString as a static method, to be invoked like

    Arrays.toString(arr_name);
    

    But the Arrays class also inherits the non-static method toString from the Object class. So if called on an instance, it invokes Object.toString which returns a string representation of the object (eg: [Ljava.lang.Object;@4e44ac6a)

    So Arrays.toString() and MyObject.toString() are calling different methods with the same name.

    The ArrayList class inherits toString from the AbstractCollection class, where it is a non static method, so can be called on the object like:

    MyArrayList.toString();
    

    Because it's a string representation of a collection and not an object, the result is the values in a readable format like [one, two].

提交回复
热议问题