Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print object content in correct way? [duplicate]

I have an ArrayList that contains some objects from User class. When I print these objects I got:

[User@18fd984, User@18fd984]

How to print these objects in a correct way?

like image 626
Mohamed Gamal Avatar asked May 08 '12 18:05

Mohamed Gamal


1 Answers

Override the method toString in the class to produce the output you prefer, instead of the default value that Java automatically generates. Example:

public class User {
   private String name;
   ...
   @Override
   public String toString() {
       return name;
   }
}

For complex objects, Apache Commons Lang provides some handy methods, if you are already using this dependency in your project:

@Override
public String toString() {
   return ToStringBuilder.reflectionToString(this);
}
like image 199
Guido Avatar answered Sep 28 '22 02:09

Guido