0

I have a array of objects. When I print it, it looks like :

[com.groups.bean.User@5a2045, com.groups.bean.User@fcabd6, com.groups.bean.User@758cdb]

I want array of values of its property "Name" like :

[John,Mike,Peter]

I know, I can iterate through the array and call property "Name" of each object and put it in a new array.

But I want to avoid looping. Is there any shortcut for it ?

Ninad Pingale
  • 6,801
  • 5
  • 32
  • 55
  • [what is the number that it shows when I print out the **this** pointer in java?](http://stackoverflow.com/questions/17878457/what-is-the-number-that-it-shows-when-i-print-out-the-this-pointer-in-java) – Suresh Atta Oct 29 '13 at 12:23
  • override toString() method for the User class to return Name – upog Oct 29 '13 at 12:23
  • 1
    you need to Owerride toString() in your class. Now works toString() of Object class, why this looks next - `com.groups.bean.User@5a2045`. – catch23 Oct 29 '13 at 12:23
  • 1
    Overload toString method in your User class and within it return name property. – Luke Oct 29 '13 at 12:25

2 Answers2

6

You can override toString() method in your User object:

public class User {
    private String name;

    @Override
    public String toString() {
        return this.name;
    }
}

You can write it w/o @Override, though. Here you can find documentation on this annotation.

aga
  • 27,954
  • 13
  • 86
  • 121
2

Override the toString() method of User.

grexter89
  • 1,091
  • 10
  • 23