- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以第一段代码返回整数数组的内存地址,但我希望它打印出实际数组。
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/
我是一名优秀的程序员,十分优秀!