Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a class printable

Tags:

java

When I print the instances of some classes (e.g. ArrayList) to a stream, e.g. System.out.println(instance of ArrayList), it doesn't print the reference id (e.g. ArrayList@2144c53d), but the actual values, with some formatting (e.g. [1,2,3,4]). I was wondering how I can do this for my own classes? Do I perhaps have to define some method/implement some interface?

like image 674
user1377000 Avatar asked Dec 04 '22 00:12

user1377000


1 Answers

Simple: you override the Object.toString() method. For example:

public class Person {
    private final String name;
    private final LocalDate birthDate;

    public Person(String name, LocalDate birthDate) {
        this.name = name;
        this.birthDate = birthDate;
    }

    @Override public String toString() {
        return String.format("%s (born %s)", name, birthDate);
    }
}

For more complex handling, you might want to consider implementing the Formattable interface - although I've never personally done so myself.

like image 51
Jon Skeet Avatar answered Dec 18 '22 04:12

Jon Skeet