Reputation: 659
I have a HashMap
. I am trying to retrieve the value and print it using the key from the user-code.
The code is:
lib.addbook(book2.getISBN(), book2);
Book ret = lib.getbook("978-81-291-1979-7");
System.out.println(ret);
Current Output:
O/P: LibraryPackage.Book@527c6768
I want the output to be a string and to display the actual value not the address of the book.
Upvotes: 1
Views: 547
Reputation: 575
You have to implement (and override) the toString()
method in your Book
class, and specify what you want the output to be. E.g.:
@Override
String toString()
{
return this.author+": " + this.title;
}
Upvotes: 5
Reputation: 11805
commons-lang has a great utility for this if you don't want to override the .toString() method, or need to represent it differently in different situations:
Here's a call to build a string based on reflection:
String str = ToStringBuilder.reflectionToString(object);
In fact, this is a great way to implement the .toString() method itself. Another alternative use of this class would be a field by field creation of the string:
String str = new ToStringBuilder(object)
.append("field1", field1)
.append("field2", field2)
.toString();
Upvotes: 0