Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

i am trying to sort arrayList using Collection sort method, but it is not working, asking me to cast and still not working

package com.otherpackage;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionPractice {

    public static void main(String[] args) {

        List<Student> list = new ArrayList<>();

        Student student1 = new Student(1, "sam");
        Student student2 = new Student(3, "raj");
        Student student3 = new Student(2, "ravi");
        Student student4 = new Student(4, "sam");

        list.add(student1);
        list.add(student2);
        list.add(student3);
        list.add(student4);

        Collections.sort(list);

        System.out.println(list);

    }

}

my collection sort method is not working, is it due to java version or any thing else i dont understand

try changing my jdk

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I guess, Student does not comparable.

implement Comparable to uses Collection.sort() like this.

public class Student implements Comparable<Student>{
...
    @Override
    public int compareTo(Student s2){
        return s2.number - this.number || s2.name.compareTo(this.name);
    }
}

or you can give comparator to Collection.sort() like this.

    Collections.sort(list, new Comparator<Student>() {
        @Override
        public int compare(Student s1, Student s2) {
            return s2.number - s1.number || s2.name.compareTo(s1.name);
        }
    });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading