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.
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;
}
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();
Related
I am quite new to Java and trying to understand the effect of using toString() while accessing the individual string elements of JSON object in Java.
Below are the steps followed:
Parse the JSON data. Let's assume only string elements are there in parsed JSON data.
JSONParser parser = new JSONParser();
JSONObject jsonObj = (JSONObject) parser.parse(json_data);
{
"firstname" : "new",
"lastname" : "human",
"id" : "some_id"
}
Try to access the individual elements.
Access without toString():
Public static String firstname = jsonObj.get("firstname");
Access with toString():
Public static String firstname = jsonObj.get("firstname").toString();
I do not see a difference when I try to print the data.
However I would like to know the difference between the above 2 methods, and also will there be any issues if I use without toString() in this particular case.
Appreciate your help.
Thank you
When you have some Int or other type of data type variables in your model class and you want to parse it into a string so for that we use toString(), it will convert int or any other data variable into a string, in your case here you already have string so no need to change again and again and JSON uses string variables when it comes from backend so that the purpose.
toString() returns string representation of property/object on which this method is called.
Whenever we print an object reference, it invokes the toString() method internally as a result , it is not making difference.
Because you are using Json, there is no difference.
You can use the Option, you like more
I tried to set value in TextView using my array logic.
Problem:
Instead of my actual value it might set address of string in
textview. I'm guessing this issue is simple, possibly not specifying .toString()?
Value that is being outputted:
com.android.carModel.Car#eacea24f
My code:
StringBuilder builder = new StringBuilder();
val = carDAO.carOutput(carId);
textbx.setText("");
for (Car details : val){
builder.append(details + "\n");
}
textbx.setText(builder.toString());
Your code is actually append someObjectClassname#hashcodenumber i.e com.android.carModel.Car#eacea24f in your case to stringBuilder. To get the desired output you need to do something like this.
`builder.append(details.getName() /*or anything*/ + "\n")`
Do you have access to the Car class? If so, add this method:
public String toString() {
return carName;
}
Replace carName with whatever you want to display. This toString() method is part of the Object class that all classes extend, and when overridden, it will change what something like a List will display.
I created a HashMap where the keys are Integers and the values are of the Employee class. Employee contains the employee's first name, last name and address. I am having issues with printing out the values. Here is what i tried.
employees.put(5, e1);
String test=employees.get(5).toString();
System.out.println(employees.toString());
System.out.println(test);
output:
{5=identitymanagement.Employee#6da264f1}
identitymanagement.Employee#6da264f1
What am I doing wrong?
A look at your code
String test=employees.get(5).toString();
This will grab the item with the key 5 in your hashmap, then call that object's toString method. The way your object is behaving at the moment implies you have no overridden that method, which is why it is printing out the objects address in memory.
System.out.println(employees.toString());
This will attempt to print out the HashMap object. In the same vain as your Employee class, HashMap does not override it's toString method, so it simply prints out the objects reference in memory.
A solution
The convention, when outputting the details of a class, is to override the toString() method. This would look something like this:
public String toString()
{
return "name: " + name;
}
When you place this method in your class, you can call the toString method and it won't just print out the memory address of the object, which is what it is doing at the moment :)
When using this code, all you have to do is pass the object to the System.out.println method and it will do the rest:
Employee e = employees.get(5);
System.out.println(e);
The correct way is
Employee e = employees.get(5); // return's Employee object stored in map with key 5
String firstName = e.firstName;
String lastName = e.lastName;
String address = e.address;
I know that the Javadocs says:
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.
But when should I spend time overriding the toString method for my classes? Should it be one of the first things I do along with overriding equals and hashCode? Or should I wait until it's actually needed?
I know Eclipse can auto generate toString methods for you, so should I just have Eclipse auto generate them once I know the fields for my class?
Josh Bloch gives a good explanation in Effective Java, in item 10.
[...] providing a good toString implementation makes your class much more pleasant to use.
It really makes it easier to output debugging traces, or makes better logging messages, since you can use the object's string representation provided by toString() directly; you don't have to manually build a string that gives the information needed on the object.
As stated in the book, you should include all the interesting information in the resulting String. You should also document properly your method; you may document the resulting String format or not, but you should at least document your intent (whether the format is subject to change, or not likely to change).
In the end, it is up to you (and your company's standards) to decide if overriding it in every class should be part of your habits or not. Personally, I don't override toString () in every classes, only in the ones which are most at risk of being used in a debuging trace.
I would implement toString() method on any class that holds human understandable non confidential data. Ex: Transfer Object, Beans, Data Object, Wrappers. For such classes just go on to implement 'toString()' method.
Classes that represent a service, process with transient states need not implement the method.Here, You can wait until it is actually needed.
Make sure you do not expose any variables with "transient" keyword in 'toString()'!
Typically, I override it when I want to assign a default format of displaying an object, often formatting a compact/digestable display of relevant attributes. So that I can simply, for example, display it in debug or log by doing:
MyClass myClsInst = new MyClass();
...
System.out.println(myClsInst);
In general, It's used to show or see what the object has.
For instance, Let's say there is a Student class and you created objects.
Student class has age, grade, gpa, name, country, address.
class Student{
private int age;
private int grade;
private double gpa;
private String name;
private String country;
private String address;
Student(...){
// ...
}
public String toString(){
String str = "age is "+age+ ", grade is " + grade + ...
return str;
}
}
And you created A student, and B student ( and maybe more )
You just need to 'toString()' for checking its inside like this:
System.out.println(aStudent.toString());
System.out.println(bStudent.toString());
or You can just write the object name, it automatically calls 'toString()'
System.out.println(aStudent);
System.out.println(bStudent);
It removes the redundant works & faster.
Then, you will see like this:
Output:
age is 13, grade is 3, ...
age is 15, grade is 5, ...
It's useful when you see what A student or B student has when you debug.
And also, It's useful when you make your own form like JSON.
It will be easier to manipulate its data with JSON format.
I am trying to demonstrate in simple way.
package com.web.doamin;
public class User {
String name;
long id;
/*#Override
public String toString() {
return "User [user = " + name + ", id="+ id + "]";
}*/
public static void main(String[] args) {
User user = new User();
System.out.println(" : user : " + user );
}
}
If we did't Override toString() method we will get Object Hash code in sysout
O/P without Override toString() method - com.web.doamin.User#7852e922
if We Override the ToString() method we will get O/P - User [user = null, id=0]
Note - It is a good idea to override toString() as we get get proper output when an object is used in System.out.println();
Is there any way in which I can automatically convert a Custom Class Object into a human readable string?
e.g. consider the following class:
class Person {
String Name;
int Salary;
...
}
Person p = new Person();
p.setName("Tony");
p.setSalary(1000);
I need to get something like:
Person: Name="Tony", Salary=1000
Importing Commons Lang you could use ToStringBuilder
Check method reflectionToString(java.lang.Object), this will create automatically the representation you are expecting.
This code:
Person p = new Person();
p.setName("Tony");
p.setSalary(1000);
System.out.println(ToStringBuilder.reflectionToString(p));
results this string:
Person#64578ceb[Name=Tony,Salary=1000]
sure you can override the toString method of class.
as follow:
class Person {
String name;
int salary;
...
#Override public String toString() {
return "Person: Name='" + name + "', Salary=" + salary;
}
}
refer for more details https://blogs.oracle.com/CoreJavaTechTips/entry/writing_tostring_methods_tech_days
This is basically what toString is for. But given you want this done automatically, you can create some general service that can do it. Use reflection to iterate all fields, and then print each one's name and value. Simplest way to print their values would be by using their toString, but you can also pass them into that printing service recursively on some cases (you'll have to find the halt condition, of course).
For example, on some class PrintUtils have:
public static void printFields(Object o) {
System.out.print(o.getClass.getSimpleName() + ": ");
for (Field field : o.getClass().getDeclaredFields()) {
field.setAccessible(true); // you also get non-public fields
System.out.print(field.getName() + " = " + field.get(o) + ", ");
}
}
You'll have to handle exceptions etc. and possibly better format the output, of course. Also, this only print fields declared in the current class. If you want fields declared higher in the inheritance hierarchy, you'll have to work a bit more. Lastly, using reflection is much slower than just having a regular toString. If using toString is possible, it is preferable.
I think you could use ToStringBuilder that is part of commons-lang.
One way to do it is to rely on Apache Commons BeanUtils.describe. This will produce a Map of bean's properties, which converts to a string nicely via Map.toString. If you want something more custom, you'll need to dig into the reflection API.
You can use message format from java :
https://docs.oracle.com/javase/tutorial/i18n//message.html
seperate variable by - and there you have a humanreadable string of your class!
class Person {
String Name;
int Salary;
...
#Override
public String toString() {
return "Person: Name = " + Name + "," +
"Salary="+Salary;
}
}
Person p = new Person();
p.setName("Tony");
p.setSalary(1000);
System.out.println(p.toString());