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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With