• Post Reply Bookmark Topic Watch Topic
  • New Topic

Overriding the .toString() method  RSS feed

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am attempting to create a substitution cipher.  The code works, but erroneously prints out the hashcode of coded_array[] rather than the contents.  I need to override the .toString() method to let Java know to apply the method to the contents rather than the array itself, but none of the examples I seem to find work.  My research has led me to believe that there is no one right way to override the .toString() method, but I simply want an easy way that works for putting the string contents of an array into a separate string variable.  I realize this question has already been asked elsewhere, but given how those answers weren't for quite the same situation and did not work for me, would anyone be willing to suggest what I do in order to put the values of coded_array[] into coded_string?  Thank you so much for your time.



PS
The commented out section is based off an example from Java for Dummies, 4th Edition, which did not work for me, and the textbook example was for a custom made class rather than an array.  Thanks.
 
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You may use Arrays.toString static method.
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look in the Java® Language Specification, which tells you that the only overridden method in an array is clone(). Then look in Object, where you will find that is the default behaviour of un‑overridden toString(). The best way round it is probably what Paweł suggested. Because your array is a local variable inside that method it is not accessible in toString().

You are using the wrong naming conventions using _ in names. Class names shou‍ld start with CapitalLetters.
 
Yassan Hikasa
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I looked up the Arrays.toString static method Paweł Baczyński mentioned and was able to get the method working.



Thanks for the help everyone, Arrays.toString(/*name of the array*/) was the command that I couldn't find.  Appreciate your insight. ^_^
 
Sheriff
Posts: 4289
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Congratulations on finding the solution and thanks for posting it.

Note on your post: code tags should surround your code.  Follow this link for how to UseCodeTags.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!