| Author |
Print Object output incorrect - Head First Java Chapter 16 TreeSet Exercise
|
Matt Hanrahan
Greenhorn
Joined: Jul 09, 2011
Posts: 13
|
|
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
Joined: Jul 26, 2007
Posts: 8430
|
|
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.
|
[Donate a pint, save a life!] [How to ask questions] [Onff-turn it on!]
|
 |
Satyen Singh
Greenhorn
Joined: Oct 05, 2011
Posts: 21
|
|
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
Joined: Jul 09, 2011
Posts: 13
|
|
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 !
|
 |
 |
|
|
subject: Print Object output incorrect - Head First Java Chapter 16 TreeSet Exercise
|
|
|