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

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

问题描述

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

对于 list [a, b, c] 是输出,而对于 array 一些地址是输出.当我们想要输出 array 值时,我们可以使用 Arrays.toString(array); ,它的工作方式就像 list.

我只是想知道为什么我们不能直接在 array 上调用 toString() 来获取值.这样做不是更直观和方便吗?ArrayArrayList 的不同处理结果是什么?

解决方案

array 和 arraylist 的主要区别在于 arraylist 是一个用 Java 编写的类,并且有自己的实现(包括决定覆盖 toString) 而数组是语言规范本身的一部分.特别是,JLS 10.7 指出:><块引用>

数组类型的成员如下:

  • 公共最终字段长度
  • 公共方法clone,覆盖类Object中的同名方法,不抛出任何检查异常.
  • 继承自类Object的所有成员;Object 唯一没有被继承的方法是它的 clone 方法.

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

为什么做出这个决定是一个可能应该问语言设计者的问题......

    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);

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.

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?

解决方案

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

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

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