【发布时间】:2014-06-29 21:26:41
【问题描述】:
我的程序旨在通过重复打印随机生成的一行来创建一首随机诗。 我有一个名为 Line 的类,它有一个可以操作的字段线:
private StringBuilder line = new StringBuilder();
构造函数如下所示:
public Line(int length, String pathOfWordList) throws IOException {
this.length = length;
populateLine(length, pathOfWordList);
}
单词列表分为三种类型的单词:名词动词和形容词,每种都有被选中的概率。
populateLine 选择并准备一个要添加到 StringBuilder 行的单词。单词是 Word 类的对象,有两个字段:
private Type wordType;
private String word;
其中 Type 是具有三种单词类型的枚举。
填充行然后通过调用调用方法的方法添加单词。 第一个方法有这个签名:
// currentWord is the word that we have to insert after.
// wordList is the word bank we draw from.
// line is the line we are working with.
// The last two doubles are the probabilities of the three types of words.
// The third one can be inferred
private void getNextWord(Word currentWord, WordList wordList,
StringBuilder line, double nounProb, double verbProb)
那个方法有一堆循环调用这个方法:
// Adds a word to the line and updates its type
// Used by getNextWord
private void loopHelper(Word currentWord, Type type, WordList wordList,
StringBuilder line) {
currentWord.setType(type);
currentWord.setWord(wordList.getWord(type));
line.append(" " + currentWord);
}
最后出于测试目的,我制作了一个打印出该行的方法:
public void printPoemLine() {
System.out.println(this.line.toString());
}
但是当我实例化并调用该方法时,我得到了这个奇怪的输出:
com.jeanlucthumm.poem.Word@7852e922 com.jeanlucthumm.poem.Word@7852e922 com.jeanlucthumm.poem.Word@7852e922 com.jeanlucthumm.poem.Word@7852e922 com.jeanlucthumm.poem.Word@7852e922 com.jeanlucthumm.poem.Word@7852e922
谁能告诉我那是什么?我只在互联网上找到了另一篇具有这种类型输出的文章,它正在处理类型擦除,但我不确定是否适用于此。
【问题讨论】:
-
提供
Word的.toString()实现。它现在向您显示在Object中指定的默认值,而您想要定义一些真正有意义的东西。 -
我通过使用 @Override 注释并定义一个 toString() 方法来做到这一点,对吗?
-
是的,完全正确。注释不是必需的,但绝对鼓励,因为如果您在方法定义中犯了错误,它会给您一个错误。
标签: java class generics stringbuilder erasure