为什么toString()方法在Java中的Array和ArrayList对象之间的工作方式不同 [英] Why toString() method works differently between Array and ArrayList object in Java

查看:633
本文介绍了为什么toString()方法在Java中的Array和ArrayList对象之间的工作方式不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    String[] array = {"a","c","b"};
    ArrayList<String> list = new ArrayList<String>();
    list.add("a");
    list.add("b");
    list.add("c");
    System.out.println(array);
    System.out.println(list);

list 输出[a,b,c] ,而对于数组输出一些地址。当我们想要输出数组值时,我们可以使用 Arrays.toString(array); 就像 list

For list [a, b, c] is output while for array some address is output. When we want to output the array values, we can use Arrays.toString(array); which works just like list.

我只是想知道为什么我们不能调用 toString()直接在数组上获取值。这样做不是更直观和方便吗?什么导致数组 ArrayList 的不同处理?

I just wonder why we can't call toString() directly on array to get the values. Isn't it more intuitive and convenient to do so? What results in the different treatments on Array and ArrayList?

推荐答案

数组和arraylist之间的主要区别在于arraylist是一个用Java编写并具有自己的实现的类(包括重写的决定toString )而数组是语言规范本身的一部分。特别是, JLS 10.7 声明:

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:


  • 公共最终字段长度

  • 公共方法克隆,它覆盖类Object中的同名方法,并且不会抛出任何已检查的异常。

  • 从Object类继承的所有成员;唯一没有继承的Object方法是它的克隆方法。

换句话说语言规范防止数组的 toString 方法被覆盖,因此它使用 Object 中定义的默认实现打印类名和哈希码。

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...

这篇关于为什么toString()方法在Java中的Array和ArrayList对象之间的工作方式不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆