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

我怕爱的太早我们不能终老 提交于 2019-12-17 07:47:56

问题


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?


回答1:


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);
}



回答2:


Look at the source code of print(Object obj) method from PrintSteam class:

public void print(Object obj)
{
    write(String.valueOf(obj));
}

and valueOf(Object obj) of String class:

public static String valueOf(Object obj)
{
    return (obj == null) ? "null" : obj.toString();
}

As you see, obj.toString() is invoked, and as @Guido García states, overriding toString() method is what you need.

The default implementation of toString() method in Object class is as follows:

public String toString()
{
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}


来源:https://stackoverflow.com/questions/10503964/how-to-print-object-content-in-correct-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!