• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Print Object output incorrect - Head First Java Chapter 16 TreeSet Exercise

 
Matt Hanrahan
Greenhorn
Posts: 14
Netscape
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello friends!

Could you tell me why when I print these objects it doesn't output the String?

Any help is appreciated!

-Matt



output:
 
Maneesh Godbole
Saloon Keeper
Posts: 11021
12
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whenever you call System.out.println(Object obj), it in turn calls obj.toString().
From the API Docs for Object#toString()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object.

What you are seeing, Book@4fe5e2c3 is nothing but the hexadecimal representation of the object hash code.
 
Satyen Singh
Greenhorn
Posts: 21
Java Tomcat Server Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code in your programme

System.out.println(b1);
System.out.println(tree);

internally it means:

System.out.println(b1.toString());
System.out.println(tree.toString());

the method toString() in the above code returns String Representation of your object's hashcode which is a unique code for each object in java.
if you want to get the String value specified by you in the Constructor as title property of your book class you must override toString() method
from the Object's Class and write your code to print the title of your book like i mentioned below.



now the code

System.out.println(b1);

will print it's title("How cats work") on your console.


 
Matt Hanrahan
Greenhorn
Posts: 14
Netscape
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Guys!

Thank you so much for the help. I appreciate your candid responses.

I overrode the toString() and it worked like a dream.

My finale code is below, and illustrates how TreeSet orders and removes duplicates.

-Matt !

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic