3

重複の可能性:
名前に基づいて連絡先の ArrayList を並べ替えていますか?

私は学生オブジェクトを持っていて、ArrayList を作成して学生をリストに追加します。

ArrayList<Student_Object> studentsList = new ArrayList<>();

ここで、リストを StudentId fleid で並べ替えたいと思います。どうすればいいですか?

より良い解決策はありますか?ありがとう


だから私は Student _Object クラスにこのメソッドを持っています

クラスは次のとおりです。

class Student_Object implements Comparator<Student_Object>

メソッドは次のとおりです。

public int compare(Student_Object student1, Student_Object student2){
    String student1TUID = student1.getTUID();        
    String student2TUID = student2.getTUID();

return student1TUID.compareTo(student2TUID);   


}

どこからステートメントを実行しますか?

Collections.sort(studentsList);

メインクラスから実行すると、netbeans でエラーが発生します。

no suitable method found for sort(ArrayList<Student_Object>)
    method Collections.<T#1>sort(List<T#1>,Comparator<? super T#1>) is not applicable
      (cannot instantiate from arguments because actual and formal argument lists differ in length)
    method Collections.<T#2>sort(List<T#2>) is not applicable
      (inferred type does not conform to declared bound(s)
        inferred: Student_Object
        bound(s): Comparable<? super Student_Object>)
  where T#1,T#2 are type-variables:
    T#1 extends Object declared in method <T#1>sort(List<T#1>,Comparator<? super T#1>)
    T#2 extends Comparable<? super T#2> declared in method <T#2>sort(List<T#2>)
----
(Alt-Enter shows hints)

動作するようになりました。Collections.sort(studentsList, new Student_Object());を使用しました。

みんな、ありがとう

4

2 に答える 2

8

1つの方法は次のとおりです。

メソッドを記述しcomparatorてオーバーライドしますcompare。次に、コンパレータを渡してCollections.sort()を使用します。

例:

class StudentComparator implements Comparator<Student> {

    public int compare(Student stud1, Student stud2){

        int stu1ID = stud1.getId();       
        int stu2ID = stud2.getId();

        if(stu1ID > stu2ID)
            return 1;
        else if(stu1ID < st21ID )
            return -1;
        else
            return 0;    
    }

}

別のフレーバーは次のとおりです。

 class StudentComparator implements Comparator<Student> {

        public int compare(Student stud1, Student stud2){

            int stu1ID = stud1.getId();       
            int stu2ID = stud2.getId();

           return stud1ID-stu2ID;
        }

    }

このチュートリアルが役立つ場合があります。

于 2012-10-24T19:43:59.297 に答える
4

並べ替えを行うには、インターフェイスを実装する必要がありComparableます。また、そこにいる間に equals と hashCode を実装することを強くお勧めします。例:

public class Student implements Comparable  
{  
    private String name;  
    private int id;  
    ...

    public int compareTo(Student otherStudent)  
    {  
       if(this.id < otherStudent.id)  
       {  
          return -1;
       }  
       else if(this.id > otherStudent.id)  
       {  
           return 1;
       }  
        else{
           return 0;  
        }  

    }  
}  
于 2012-10-24T19:46:37.487 に答える