按字母顺序对二维数组进行排序

时间:2013-10-14 13:55:43

标签: java

我正在整理2D数组并遇到一些问题。当我排序它开始为第一对夫妇工作,但没有完成。这是我的代码,然后我将发布我的输出.sectionArray []的第一部分包含2个部分。在sectionArray [] []的第二部分包含不同的学生对象。我需要按字母顺序为每个部分排序这些对象的字符串名称。

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);

            }
        }
    }

}

输出:

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

1 个答案:

答案 0 :(得分:2)

也许您可以使用比较器:

Arrays.sort(myList, new Comparator<Student>() {
    @Override
    public int compare(Student s1, Student s2) {
        return s1.getName().compareTo(s2);
    }

});
相关问题