创建对象的列表/ arraylist并对列表进行排序(Java)

时间:2012-10-24 19:42:47

标签: java arrays object arraylist

  

可能重复:
  Sorting an ArrayList of Contacts based on name?

我有一个学生对象,然后我创建了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());

谢谢大家

2 个答案:

答案 0 :(得分:8)

一种方法是:

撰写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;
        }

    }

tutorial可能会对您有所帮助。

答案 1 :(得分: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;  
        }  

    }  
}