1.我试图按标题按字母顺序对歌曲列表进行排序,但所有发生的事情都是列表按相反顺序排列然后输出。
public void sort()
{
//create a pointer to hold the temp for switching
MusicHW02 temp;
//two nested loops. Go through entire list less 1
for (int index = 0;index< count -1;index++) {
/*inner for loop to go through list starting with next index
*to see if smaller
*/
for(int index2= index +1; index2<count; index2++) {
//Sort method to compare Strings
if(collection[index2].getTitle().compareTo(collection[index].getTitle())<0);{
temp = collection[index2];
collection[index2] = collection[index];
collection[index] = temp;
}//END OF IF STATEMENT
}//END OF INNER FOR LOOP
}//END OF OUTER FOR LOOP
}//END OF SORT METHOD
答案 0 :(得分:2)
删除if语句末尾的分号,因为它将被视为n空语句
if(collection[index2].getTitle().compareTo(collection[index].getTitle())<0);{}
到
if(collection[index2].getTitle().compareTo(collection[index].getTitle())<0){}
为什么不使用
Collections.sort(someList);
或
Arrays.sort(someArray);
或类似的东西
String arr[] ={"abc","def","adf","acb"};
Collections.sort(Arrays.asList(arr),new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
System.out.println(Arrays.toString(arr));
答案 1 :(得分:0)
您应该使用比较器。这将使您可以根据需要灵活地进行排序。我把它扔在一起,但它应该帮助你做你想要的。这确实是泡泡排序顺便说一下。使用比较器,您还可以在排序之前将它们转换为所有大写/小写,这样即使字符串大小写不匹配,您也总是按正确的顺序排列它们。
Coparator<String> songComparator = new Comparator<String>() {
public int compare(String str1, String str2) {
if (str1 == null) {
return 0;
}
return (str2 != null) ? str1.compareTo(str2) : 1;
}
}
Arrays.sort(<collection you want to sort>, songComparator);
以下是一个很好的示例列表http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/