ArrayList的奇怪输出 [英] strange output from ArrayList
问题描述
我是Java的新手,我遇到了ArrayList中对象的问题。
I'm new to Java and i'm having an issue with objects in ArrayList.
我正在尝试放置一个带有文本和时间戳的对象在ArrayList中。
一开始它表现正常,因此您可以输入注释,如果键入exit,它将关闭Input并显示ArrayList中的所有条目。
但是如果我输入exit它只显示我的输出:
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
Notizblock@4c15c0d7
这是我的代码:
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.
谢谢
PS我是德国人,抱歉我的英文不好;)
P.S. I'm german, sorry for my bad english ;)
推荐答案
你需要覆盖 toString
方法。 Notizblock
是一个自定义类,默认 System.out
将是 classname @ hashcode <对象的/ code>,这就是你所看到的。
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.
一旦你覆盖 toString
它将根据 toString
实现打印对象的内容。下面是一个示例:
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());
}
toString()
。这就是为什么重写 toString()
将是一个更好的方法,然后提供一个自定义方法来执行相同的工作,除非你正在做一些额外的/特殊的数据格式。
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.
这篇关于ArrayList的奇怪输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!