Sygnerical
Sygnerical

Reputation: 221

Printing out ArrayList with toString

When I create an ArrayList object and add other objects to it, printing out the ArrayList object will print out the memory references of the objects inside. However, if I add String to the ArrayList object, it will not print out the memory references of the String but rather the actual String value. String is also an object of a class right, so why does it not print out the String memory reference?

Upvotes: 2

Views: 2422

Answers (3)

user10937286
user10937286

Reputation: 351

toString() method of Object class is overridden by Class AbstractCollection. ArrayList extends AbstractList and AbstractList extends AbstractCollection. Method detail is mentioned below.

public String toString() 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).

Overrides: toString in class Object

Returns: a string representation of this collection

Upvotes: 0

Bohemian
Bohemian

Reputation: 424993

When you print a List, the List's toString() method is called, which in turn calls to toString() method of its elements.

The Object, which every class extends, class has a toString() method that creates the "memory address" output you're seeing (actually it's not the memory address, but anyway). The String class overrides the toString() method to return its contents.

To fix the output "problem", override the toString() method in you classes of the other objects you're adding to your List to return something "human readable".

Upvotes: 1

ggmathur
ggmathur

Reputation: 843

The toString method for a Collection in Java (which is what an ArrayList extends) uses String.valueOf on each of its elements: http://docs.oracle.com/javase/7/docs/api/java/util/AbstractCollection.html#toString()

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

String.valueOf is simply grabbing the toString value of the object: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#valueOf(java.lang.Object)

if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

Upvotes: 3

Related Questions