3

Possible Duplicate:
Sorting an ArrayList of Contacts based on name?

I have a student object and then I create ArrayList and add student to the list.

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

Now, I want to sort the list by studentId fleid. How can I do it?

Is there a better solution? Thanks


So I have this method in the Student _Object class

Class is:

class Student_Object implements Comparator<Student_Object>

The method is:

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

return student1TUID.compareTo(student2TUID);   


}

From where do I run the statment?

Collections.sort(studentsList);

If I run it from my main class I get error in 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)

Got it to work. I used Collections.sort(studentsList, new Student_Object());

Thanks everyone

2
  • Student_Object is redundant, just use Student Commented Oct 24, 2012 at 19:44
  • @RohitJain in reality it should be combined and a new question of the form "Sort list based on arbitrary field", however those combinations seem to get knocked down. Commented Oct 24, 2012 at 19:47

2 Answers 2

8

One way would be:

Write a comparator and override compare method. Then use Collections.sort() by passing comparator.

Example:

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

}

Another flavor may be:

 class StudentComparator implements Comparator<Student> {

        public int compare(Student stud1, Student stud2){

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

           return stud1ID-stu2ID;
        }

    }

This tutorial may help you.

Sign up to request clarification or add additional context in comments.

14 Comments

Better implement a generic Comparator. No typecast needed. And why not just do: - return stuID1 - stud2ID;??
@RohitJain: The tutorial I have added as reference not using generics, I thought that may confuse OP. Thanks for edit.
@RohitJain: I guess stud1-stud2 is not guaranteed to return either 1, -1, 0. Sometimes it could be higher vlaue, isn't it?
You're welcome. You can also consider returning simply the difference, rather than that if-else block. that will do the job. :)
Yeah but does it matter? sort method just care about, positive or negative value, or 0 for equal.
|
4

To do sorting you need to implement the Comparable interface. I would also highly recommend implementing equals and hashCode while you are in there. Example:

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

    }  
}  

5 Comments

public int compareTo(Student otherStudent) { return this.id - otherStudent.id; } will do the job, too ;)
@jlordo indeed it will,not sure which is faster though, doing a calculation or doing a logical compare.
please change your return type to int
@jlordo to quick on the typing =p
Performance is an interesting point, does anyone know how the resulting bytecode looks?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.