[英]Sorting an 2d array in alphabetical order
I am sorting a 2D array and am having a few issues. 我正在排序一个2D数组,我遇到了一些问题。 When i sort it starts to work for the first couple and doesn't finish. 当我排序它开始为第一对夫妇工作,但没有完成。 Here is my code then I will post my output.The first part of sectionArray[] contains 2 sections. 这是我的代码,然后我将发布我的输出.sectionArray []的第一部分包含2个部分。 In the second part of sectionArray[][] contains different student objects. 在sectionArray [] []的第二部分包含不同的学生对象。 I need to sort these object's String names alphabetically for each section. 我需要按字母顺序为每个部分排序这些对象的String名称。
public void sortByName(){
String temp;
for(int i = 0; i < 2; i++){
for (int a = 0; a < sectionArray[i].length-1; a++){
if (sectionArray[i][a].getName().compareToIgnoreCase(sectionArray[i][a+1].getName()) > 0){
temp = sectionArray[i][a].getName();
sectionArray[i][a].setName(sectionArray[i][a+1].getName());
sectionArray[i][a+1].setName(temp);
}
}
}
}
Output: 输出:
Progress Report
Section 1
Johnson 90.6 A
Aniston 81.2 B
Cooper_ 82.2 B
Gupta__ 72.2 C
Blair__ 52.2 F
Section 2
Clark__ 59.2 F
Kennedy 63.4 D
Bronson 90.0 A
Sunny__ 84.8 B
Smith__ 75.4 C
Diana__ 68.8 D
AFTER SORTING THE 2D ARRAY
Progress Report
Section 1
Aniston 90.6 A
Cooper_ 81.2 B
Gupta__ 82.2 B
Blair__ 72.2 C
Johnson 52.2 F
Section 2
Clark__ 59.2 F
Bronson 63.4 D
Kennedy 90.0 A
Smith__ 84.8 B
Diana__ 75.4 C
Sunny__ 68.8 D
Perhaps you could just use a comparator : 也许你可以使用一个比较器:
Arrays.sort(myList, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return s1.getName().compareTo(s2);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.