【发布时间】:2012-05-06 21:06:15
【问题描述】:
我正在创建一个由多个作者撰写的文章的数据库,所以我有两个类:作者和文章。 Article 的构造函数是
Article(String title, String venue, Author[] authors, long year).
一个 Author 对象包含一个带有作者姓名的字符串和一个他写过的文章的 ArrayList。
所以,我有一个文章数组,我正在尝试创建一个作者数组列表并添加他们写的所有文章。
这是我的代码:
for(int i=0; i<allarticles.length; i++) {
Author[] tempauthors = allarticles[i].getAuthors();
for (int j=0; j<tempauthors.length; j++) {
Author tempauthor = tempauthors[j];
if (authors.contains(tempauthor)) {
Author oldAuthor = authors.get(authors.indexOf(tempauthor));
if (!oldAuthor.hasArticle(allarticles[i]))
oldAuthor.addArticle(allarticles[i]);
} else {
if (!tempauthor.hasArticle(allarticles[i]))
tempauthor.addArticle(allarticles[i]);
authors.add(tempauthor);
}
}
}
这里是 hasArticle 方法: public boolean hasArticle(Article a) { 返回articles.contains(a); }
我按照建议修改了 equals 方法,但现在的问题是我得到的作者拥有适量的文章,但第一个是重复的。我做错了什么?我也应该覆盖 Article.equals() 方法吗?
【问题讨论】:
-
重读关于对象引用、身份和
equals()的章节。