1

Can you explain why this code

int[] test={0,0,0,0,0};
System.out.println(test);

prints something like [I@42e816 (perhaps memory address) but this code

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

prints "[1, 3, 5, 2, 4]"? What's the difference?

If Stacks derive from Vectors and Vectors from arrays, what's the cause of this different behavior?

Surfer on the fall
  • 721
  • 1
  • 8
  • 34

3 Answers3

5

The collections have a well defined toString() method, but arrays were forgotten about IMHO and use the default Object.toString() along with lots of other default method from Object which are not very useful either. You need to call one of the many helper classes were added later to make arrays more useful.

System.out.println(Arrays.toString(test));

The hexidecimal is the default hashCode() of the object rather than an address. It might not be unique and even if the array moves around the memory, this number won't change.

For helper classes for arrays

java.lang.reflect.Array
java.util.Arrays
java.lang.System.arraycopy(); // one method

for extra ones

org.apache.commons.lang.ArrayUtils
org.uispec4j.utils.ArrayUtil
toxi.util.datatypes.ArrayUtil
net.sf.javaml.utils.ArrayUtils
com.liferay.portal.kernel.util.ArrayUtil

and many more.

It not the case that arrays shouldn't have their own methods but rather there is too many to choose from. ;)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
4

Stack has an overridden toString() method which iterates through each element and prints them and hence you see the formatted print.

You can use Arrays.toString(test) to print the contents of an array in foratted way. As of now you are doing a toString on the array object rather that it's contents.

You can refer this to understand the default toString() implementation of the array object and hence the output you notice when printing test array.

Community
  • 1
  • 1
Scorpion
  • 3,938
  • 24
  • 37
1

Stack > Vector > AbstractList > AbstractCollection.

AbstractCollection defines toString(), which is what gets called by System.out.println to get the string representation.

int[] is not one of these object types - it is a native array, so it uses the default implementation of toString in Object class.

Krease
  • 15,805
  • 8
  • 54
  • 86