Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Need Some Explanation for ArrayList toString Method  RSS feed

 
Saket Kumar Sinha
Ranch Hand
Posts: 32
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wrote the following code


It gives me output
After Modification [30, [40, 50, 60], 20]
As i have added a list after position 1 and calling tostring Method on alList not on alList1. How the data of alList1 also getting properly.
I know the toString() is overridden but just can't believe that it prinitng the values for innerList at position 1 also.
Can any one help me here? What i am not able to think
 
Saket Kumar Sinha
Ranch Hand
Posts: 32
Eclipse IDE Java Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think i have got the answer for myQuestion.
toString() method is automatically called while printing only object. and hence the innerList object toString method is called and the values are printed.
 
Kemal Sokolovic
Bartender
Posts: 825
5
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the API:

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


Which means that it prints all the elements as they are ordered in your list. When it comes to second element, toString() is invoked on list which returns what's stated above, etc.
 
Saket Kumar Sinha
Ranch Hand
Posts: 32
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI Kemal, Thanks for the response. I understood the concept.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!