Why does ArrayList print the actual value and not the memory address?

Viewed 655

In Java, I understand primitive data types are stored as a value and the rest are stored as references. Then why is it that I get the actual value but not the memory address when I print ArrayList instance variable? I have an array variable just for comparing purposes.

    public static void main(String[] args) {

        Object[] a = new Object[3];
        a[0] = 0;
        a[1] = 1;
        a[2] = 2;

        ArrayList<Object> b = new ArrayList<Object>();
        b.add(3);
        b.add(4);

        System.out.println(a);
        System.out.println(b);

    }
3 Answers

Two reasons

  • Because the Object.toString() method has been overridden.
  • Because the javadocs says that the toString() method for any type that extends the AbstractCollection class will display the collection's contents, not its "address".

And besides Object.toString() doesn't actually display the address anyway. It displays the identity hashcode with might be related to the address of the object, or it might not. (And two distinct objects can have the same identity hashcode, so it is not a reliable indicator that objects are the same.)

If you want to test if two object references (of any type) refer to the same object, use ==.

You don't need to look at addresses, and even if you figure out how to get the real address of an object ... object addresses change when the GC moves them, so this may not a 100% reliable way to test the objects.

You can discover why on your own. Just follow the documentation.

The println method takes a String object. See its Javadoc. To quote:

Prints an Object and then terminate the line. This method calls at first String.valueOf(x) to get the printed object's string value, then behaves as though it invokes print(String) and then println().

That means a call is made to the toString method on the collection object you pass to println.

So look at the Javadoc for the toString method inherited by ArrayList. To quote:

Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).

Related