ClassCastException:: cannot be cast to class java. Processing method of lang. comparable

When inserting a custom object into a data structure such as TreeSet, the following code is used:

public class demo {
    public static void main(String[] args) {
        TreeSet<Person> data = new TreeSet<>();
        Person person1 = new Person("Edmond",17);
        Person person2 = new Person("John",19);
        data.add(person1);
        data.add(person2);
        for(Person p : data){
            System.out.println(p);
        }
    }

    static class Person{
        private String name;
        private int age;

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }
}

The system will report an error when adding for the first time:

The reason is that when we save the data into TreeSet, the internal sorting will be carried out automatically. For example, we save 'a', 'C', 'B', and 'a', 'B' and 'C' will be displayed during printout. Therefore, if the data type we store is user-defined, the system will not know how to sort.

Therefore, we need the implementation comparable interface and define our own comparison rules. The demonstration code is as follows:

public class demo {
    public static void main(String[] args) {
        TreeSet<Person> data = new TreeSet<>();
        Person person1 = new Person("Edmond",19);
        Person person3 = new Person("Tom",9);
        data.add(person1);
        data.add(person2);
        data.add(person3);
        for(Person p : data){
            System.out.println(p);
        }
    }

    static class Person implements Comparable<Person>{
        private String name;
        private int age;

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public int compareTo(Person o) {
            //this当前对象 与 o 比较
            //返回数据有三种类型:
            //整数 : 代表this当前对象较大
            //0   :  代表一样大
            //负数 : 代表this当前对象较小
            if(this.age > o.age){
                return 1;
            }else if(this.age == o.age){
                return 0;
            }
             return -1;
             //可以简写为return this.age - o.age;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ",age=" + age +
                    '}';
        }
    }
}

No error is reported, and the output is:

summary

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>