13

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?

Sufian
  • 6,405
  • 16
  • 66
  • 120
Mohamed Gamal
  • 131
  • 1
  • 1
  • 3
  • That is correct--the default Object toString output. Define "correct" for your usecase. – Dave Newton May 08 '12 at 18:04
  • 4
    Object's `toString` returns `getClass().getName() + '@' + Integer.toHexString(hashCode())`. You have to override this method for your class per Guido García's answer. – Tyler Treat May 08 '12 at 18:05

2 Answers2

13

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);
}
Guido
  • 46,642
  • 28
  • 120
  • 174
1

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());
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417