打印数组:内存地址或其内容?

Sur*_*all 1 java arrays vector

你能解释为什么这个代码

int[] test={0,0,0,0,0};
System.out.println(test);
Run Code Online (Sandbox Code Playgroud)

打印像[I @ 42e816(也许是内存地址)但是这段代码

 Stack<Integer> stack = new Stack<Integer>();
 stack.push(1);
 stack.push(3);
 stack.push(5);
 stack.push(2);
 stack.push(4);
 System.out.println(stack);
Run Code Online (Sandbox Code Playgroud)

打印"[1,3,5,2,4]"?有什么不同?

如果Stacks派生自数组中的Vectors和Vectors,那么这种不同行为的原因是什么?

Pet*_*rey 5

集合有一个定义良好的toString()方法,但数组被遗忘了恕我直言,并使用默认的Object.toString()以及许多其他非常有用的默认方法.您需要调用之后添加的许多辅助类之一,以使数组更有用.

System.out.println(Arrays.toString(test));
Run Code Online (Sandbox Code Playgroud)

十六进制是对象的默认hashCode()而不是地址.它可能不是唯一的,即使数组在内存中移动,这个数字也不会改变.

对于数组的辅助类

java.lang.reflect.Array
java.util.Arrays
java.lang.System.arraycopy(); // one method
Run Code Online (Sandbox Code Playgroud)

额外的

org.apache.commons.lang.ArrayUtils
org.uispec4j.utils.ArrayUtil
toxi.util.datatypes.ArrayUtil
net.sf.javaml.utils.ArrayUtils
com.liferay.portal.kernel.util.ArrayUtil
Run Code Online (Sandbox Code Playgroud)

还有很多.

不是数组不应该有自己的方法,而是有太多的选择.;)