Home > Back-end >  Sorting Custom Objects with Collections.sort()
Sorting Custom Objects with Collections.sort()

Time:12-14

I am trying to sort custom objects using Collections.sort in java and I am running into this error, with the following code:

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

public class StudentClient {
   public static void main(String[] args){
      ArrayList<Student> students = new ArrayList<Student>();
      students.add(new Student("Jasper Holton", 12));
      students.add(new Student("John Doe", 10));
      ArrayList<Student> sortedStudents = Collections.sort(students);
      System.out.println(sortedStudents);
   }
}
public class Student implements Comparable<Student> {
   public String name;
   public int id;
   public Student(String name){
      this.name = name;
   }
   public Student(String name, int id){
      this.name = name;
      this.id = id;
   }
   ...
   @Override
   public int compareTo(Student s){
      return s.id - this.id;
   }
}

This is the error:

StudentClient.java:14: error: incompatible types: void cannot be converted to ArrayList<Student>
      ArrayList<Student> sortedStudents = Collections.sort(students);

How do I fix this error? Why is collections.sort returning a void type?

CodePudding user response:

This is a compile time error. sort works on the same list you provide, it doesn't return a new one.

So just change this:

ArrayList<Student> sortedStudents = Collections.sort(students);
System.out.println(sortedStudents);

For this

Collections.sort(students);
System.out.println(students);

Update: Reference documentation

All java classes are well documented on what's named javadoc (java documentation). There you can find every specification of classes, methods, return types, etc, etc, with explanations and sometimes even examples.

In your case, a quick look here would have been really helpful:

https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html

CodePudding user response:

In a more functional style, your main method can be written using streams:

public static void main(String[] args){
    List<Student> students = List.of(new Student("Jasper Holton", 12), new Student("John Doe", 10));
    List<Student> sortedStudents = students.stream().sorted().collect(Collectors.toList());
    System.out.println(sortedStudents);
}

It is also possible to rewrite your Student class slightly, using private where possible:

public class Student {
    private final String name;

    private int id;

    public Student(String name){
      this.name = name;
    }

    public Student(String name, int id){
      this.name = name;
      this.id = id;
    }
}
  •  Tags:  
  • java
  • Related