【发布时间】:2015-08-05 02:04:11
【问题描述】:
我目前正在编写一个打印书籍 ArrayList 的程序。 book 元素的每个 ArrayList 都由一个字符串(书名)和一个 ArrayList(该书的作者)组成。我需要对我的 ArrayList 书籍进行排序,以便它们按字母顺序显示(按标题排序)。我的问题是,当我打印新的 ArrayList(我调用 Collections.sort() 的列表)时,我得到的输出与我第一次打印非排序版本时相同。
我从我的驱动程序调用myLib.sort();,该驱动程序转到我的库类中的这个方法:
public void sort()
{
Collections.sort(myBooks);
}
myBooks 是我前面提到的书籍的 ArrayList。根据我的阅读,Collections.sort("ArrayList name") 应该按字母顺序对我的列表进行排序。如果这是不正确的,我需要使用compareTo() 和equals() 方法,那么这里是出现在class Book 中的那些方法,我用来构建进入我的class Library 的书籍:
public int compareTo(final Book theOther)
{
int result = 0;
if (myTitle.equals(theOther.myTitle))
{
if (myAuthors.get(0) != theOther.myAuthors.get(0))
{
result = 1;
}
}
else
{
result = 0;
}
return result;
}
public boolean equals(final Object theOther)
{
if (theOther instanceof String)
{
String other = (String) theOther;
return myTitle == other;
}
else
{
return false;
}
}
我能想到的唯一剩下的可能问题是我的打印方法。我的驱动程序打印 myLib 这是一个库。我的图书馆类有以下toString() 方法:
public String toString()
{
String result = "";
for (int i = 0; i < myBooks.size(); i++)
{
String tempTitle = myBooks.get(i).getTitle();
ArrayList<String> tempAuthors = myBooks.get(i).getAuthors();
Book tempBook = new Book(tempTitle, tempAuthors);
result += (tempBook + "\n");
}
return result;
}
这会从我的 Book 类 toString() 方法中获取每本书和该书的字符串,如下所示:
public String toString()
{
return "\"" + myTitle + ",\" by " + myAuthors;
}
如果这太少、太多、太混乱、不够清楚等等......请在评论中告诉我,我会尽快编辑帖子。如果需要,我还可以发布我的三个课程的全部内容。我是 Java 新手,而且在发帖方面也很新,所以我仍然习惯于两种情况下的工作方式,所以如果你对我放轻松,我将不胜感激。谢谢!
【问题讨论】:
-
尝试将“return 0”改为“-1”,
-
@BachT 当我这样做时,我的程序会为我的每本书打印诸如 Book@5c647e05 之类的内容。
-
public int compareTo(final Book theOther) { int result = myTitle.compareTo(theOther.myTitle); if (result == 0) { if (myAuthors.get(0) != theOther.myAuthors.get(0)) { result = 0; } } 返回结果; }
-
试试看是否有效?
-
@BachT 我应该编辑我的帖子并添加所有代码,还是在与您的私人聊天中这样做会更好?
标签: java sorting arraylist collections tostring