strange output from ArrayList [duplicate]

2019-03-03 03:10发布

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 ;)

1条回答
老娘就宠你
2楼-- · 2019-03-03 03:53

You need to override toString method. The Notizblock is a custom class, the default System.out will be classname@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 your toString implementation. Here is a sample:

@Override
public String toString() {
  return "Notizblock {" +
      "text='" + text + '\'' +
      ", datum='" + datum + '\'' +
      '}';
}

Yes. You can call the existing print method which you have defined.

System.out.println("alle notizen:");
for (Notizblock notiz :notizen ) {
    System.out.println(notiz.print());
}

The toString() is called automatically when you print (SOUT) anything. That is why overriding toString() 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.

查看更多
登录 后发表回答