This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
The ArrayList class internally maintain an array. When I print ArrayList object I get the list element seperated by comma where as in case of array object I get the memore address. why the ArrayList element is printed seperated by comma and I don't get the memory address just like array when I print the list object?
This behaviour is because of the ways in which toString() method is implemented in class Object and class ArrayList (ArrayList overrides Object's toString() method).
toString() of Object prints class name, followed by '@' symbol, followed by hashCode of that object.
toString() of ArrayList prints all the members of the list within square brackets, and members are separated by comma (','). How each member of that list is printed will further be decided on that class' toString() method. e.g. while printing ArrayList of Employee, first toString() of ArrayList will be called, followed by toString() method for all members (i.e. toString() method of Employee class - if it is overridden. Otherwise, toString() of Object will be called).
The println method checks if the object that it needs to print has a toString method defined. If it has then it uses that. The fact that you are able to see the list contents when using the println method should state the same. So, please check if the List class has the method toString overridden.
However, if an object doesn't have this method overriden, the toString() method from Object class gets picked up and we get to see the hashcode. Verify Objects toString method.
The println method checks if the object that it needs to print has a toString method defined.
No, it doesn't. All objects have a toString() method, and println() just calls it; it doesn't check first. (Actually, it's not toString() that calls it, but some other method that toString() calls, like String.valueOf().)