javasortingarraylistcollectionscompareto

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


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