-2

Using Java 8, I was checking out some of its new features...

Created the following class:

public class Person {

    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Created the PersonApp class:

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import static java.util.Comparator.comparing;

public class PersonApp {

    public static void printSorted(List<Person> people, Comparator<Person> comparator) {
        people.stream()
              .sorted(comparator)
              .forEach(System.out::println);
    }

    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();

        people.add(new Person("Sara", 12));
        people.add(new Person("Mark", 43));
        people.add(new Person("Bob", 12));
        people.add(new Person("Jill", 64));

        printSorted(people, comparing(Person::getAge).thenComparing(Person::getName));
    }
}

When I run this class, I get the following instead of the values I wanted to see:

Person@682a0b20
Person@3d075dc0
Person@214c265e
Person@448139f0

What am I possibly doing wrong?

PacificNW_Lover
  • 4,746
  • 31
  • 90
  • 144
  • 1
    Override `toString()` in `Person`. – Andy Turner Aug 20 '16 at 23:07
  • Refer to http://stackoverflow.com/questions/29140402/how-do-i-print-my-java-object-without-getting-sometype2f92e0f4. – Tunaki Aug 20 '16 at 23:10
  • I'm quite surprised you're able to write stream code but don't know about `toString`. Are you learning the language in the right order ? – Dici Aug 20 '16 at 23:16

1 Answers1

7

Short answer: You are missing a toString implementation in your Person class.

Explanation: System.out.println calls the toString method on the passed object and prints the output.

In this case you are passing a Collection(List) to be printed, which in turn calls the toString method on each member of the collection (see implementation of AbstractCollection.toString), which in this case happen to be objects of your Person class.

Since you haven't overridden toString in your Person class, Object.toString gets invoked (all Java classes implicitly extend Object class), and that's why you get the output as Person@123456, because Object.toString is implemented as:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
} 
rohitvats
  • 1,811
  • 13
  • 11
  • Np, but your answer is a bit short. Although it's a basic question which problem has a hundred duplicates, you could explain it a bit better. – Dici Aug 20 '16 at 23:12