This question already has an answer here:
I'm new to Java and i'm having an issue with objects in ArrayList.
I'm trying to put a object with a text and a timestamp in a ArrayList. At the start it behaves correctly, so you can type your notes in and if you type "exit" it closes the Input and shows all entries from the ArrayList. But if i type "exit" it just shows me this output:
Notizblock@4c15c0d7
This is my code:
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Scanner;
import java.util.ArrayList;
class Notizblock {
//heutiges Datum erzeugen
private static String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyy HH:mm:ss");
Date datum = new Date();
return dateFormat.format(datum);
}
private String text;
private String datum;
//Konstruktor
public Notizblock(String text, String datum){
this.text = text;
this.datum = datum;
}
public void print() {
System.out.println("Datum: "+datum+" Text: "+text);
}
public static void main(String[] args) {
ArrayList<Notizblock> notizen = new ArrayList<Notizblock>();
Scanner eingabe = new Scanner(System.in);
while (true) {
System.out.println("Notiz eingeben:");
String a = eingabe.next();
if (a.equals("exit")) {
break;
}
notizen.add(new Notizblock(a, getDateTime()));
}
System.out.println("alle notizen:");
for (Notizblock notiz :notizen ) {
System.out.println(notiz);
}
}
}
I'm glad if anyone could tell me what i'm doing wrong, I'm open for every improvment to my code.
Hit me up if you need some more Information.
Thanks
P.S. I'm german, sorry for my bad english ;)
You need to override
toString
method. TheNotizblock
is a custom class, the defaultSystem.out
will beclassname@hashcode
of the object, which is what you are seeing.once you override the
toString
it will print the content of the object as per yourtoString
implementation. Here is a sample:Yes. You can call the existing print method which you have defined.
The
toString()
is called automatically when you print (SOUT) anything. That is why overridingtoString()
will be a better approach then providing a custom method for doing the same job, unless you are doing some extra/special formatting of the data.