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

Why does ClassCastException occur this code?

import java.util.Arrays;
class Person {
    String name;
    int age;
    public Person(String name, int age) {
        this.name = name; this.age = age;
    }
    @Override
    public String toString() {
        return name + ": " + age;
    }
}
class ObjSort {
    public static void main(String[] args) {
        Person[] arr = new Person[3];
        arr[0] = new Person("Stephen", 31);
        arr[1] = new Person("Richard", 24);
        arr[2] = new Person("Bachman", 50);
        Arrays.sort(arr);
        for (Person p : arr)
            System.out.println(p);
    }
}

I want to sort in descending order by age.
When I run it, the problem occurs with Arrays.sort(arr);
How should I fix the Person class?

Exception in thread "main" java.lang.ClassCastException: class Person cannot be cast to class java.lang.Comparable (Person is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')
    at java.base/java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:320)
    at java.base/java.util.ComparableTimSort.sort(ComparableTimSort.java:188)
    at java.base/java.util.Arrays.sort(Arrays.java:1040)
    at ArrayObjSort.main(ArrayObjSort.java:25)

Added error log.

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 :

The Arrays.sort() is expecting an array of objects that are comparable.

You need to make your Person class comparable.

class Person implements Comparable<Person> {
    String name;
    int age;
    public Person(String name, int age) {
        this.name = name; this.age = age;
    }
    @Override
    public String toString() {
        return name + ": " + age;
    }

    public int compareTo(Person p){
        return name.compareTo(p.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