Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

    }
like image 817
John Kang Avatar asked Dec 12 '25 12:12

John Kang


1 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.

like image 68
Stephen C Avatar answered Dec 15 '25 05:12

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!