gpt4 book ai didi

java - 为什么要打印数组的内存地址

转载 作者:行者123 更新时间:2023-12-03 21:34:44 25 4
gpt4 key购买 nike

所以第一段代码返回整数数组的内存地址,但我希望它打印出实际数组。

import java.util.Arrays;
public class FinalsReview{
int[] list = new int[]{12, 435,546, 7, 24, 4, 6, 45, 21, 1};
public static void main(String[]args){
FinalsReview hello = new FinalsReview();
System.out.print(hello.create());
}
public int[] create(){
Arrays.toString(list);
return list;
}
}

但是,下面的代码打印出实际的数组。

import java.util.Arrays;
public class FinalsReview{
int[] list = new int[]{12, 435,546, 7, 24, 4, 6, 45, 21, 1};
public static void main(String[]args){
FinalsReview hello = new FinalsReview();
hello.create();
}
public void create(){
System.out.println(Arrays.toString(list));
}
}

为什么第一个返回内存地址?

最佳答案

它不是内存地址,它是 hashCode()toString()Object 中定义的类名,当您没有为 int[] 类指定 toString() 方法时,您将从 Object

继承它

实现方式如下

public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

虽然此 Arrays.toString(list) 显式迭代 Collection 并打印每个元素的值

为什么会这样from http://bugs.java.com/view_bug.do?bug_id=4168079

One caveat: the toString() method is often used in printing diagnostics. One would have to be careful if very large arrays were involved. The Lisp language deals with this using the print-level/print-length mechanism. Something similar would be needed in Java as well. In practice, the 'toString' method provided in every class should be preferred as the brief option suitable for use in concise diagnostics, and a more verbose representation provided by additional application-specific conversion methods if needed by the application logic.

Regardless of its technical merit, however, it is doubtful that we can make such a change at this late date due to compatibility/stability concerns.

william.maddox@Eng 1998-08-31

I concur. It would definitely have been the right thing in 1.0, or maybe even 1.1, but it's almost certainly too late for all of these changes except perhaps the toString change. One consolation is that it's amazingly easy

关于java - 为什么要打印数组的内存地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27495525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com