Have you mastered the three major interfaces of Comparable, Comparator, and Cloneable?

I was doing a question recently,

I found myself weak in this respect,

The following knowledge has been reviewed and sorted out:

Hope it will be helpful to you too~~~~~~

content

1. Comparator

1.1Comparable interface

1.2Comparator interface

2. Cloneable interface

2.1 Deep copy and shallow copy


1. Comparator

①Introduction of comparator

a. First of all, when we compare arrays of a certain data type, we can directly use Arrays.sort() for implementation

b. When we have multiple parameters at the same time, it does not tell us what to sort by. At this time, if we use Arrays.sort(), an error will occur.

 Based on this situation, we learned that if we want to compare the size of a custom type, we must introduce an interface that can implement the comparison. Let's introduce the two comparators, Comparable and Comparator.

1.1Comparable interface

① Implement the operation of the Comparable interface

②The sorting of age is realized through the Comparable interface

 ③ Implement the sorting of names through Comparable (note that the name is a reference class, and compareTo() should be used for comparison)

④ ascending descending order

Since the final comparison is performed by using Arrays.sort(), the bottom layer of this method is an ascending order operation. If you want to convert to descending order, you only need to exchange the two positions in the rewritten compareTo() method.

The result of running the code after changing to descending order:

 ⑤ Disadvantages! ! !

Comparable has a strong inclination towards classes. From the above, we can see that if we want to compare new types, we need to change the types in compareTo() and compare them again. This will most likely cause logical problems and readability problems in the entire code in future work. Therefore, we introduce the following A type of Comparator interface that is very flexible and not strong in inclination
⑥ The overall code is as follows:

import java.util.Arrays;
class Student implements Comparable<Student> {
    public int age;
    public String name;
    public double score;
    public Student(int age,String name,double score){
        this.age=age;
        this.name=name;
        this.score=score;
    }
     @Override
     public String toString() {
         return "Student{" +
                 "age=" + age +
                 ", name='" + name + '\'' +
                 ", score=" + score +
                 '}';
     }

    public static void main3(String[] args) {
        Student student1=new Student(12,"张三",98.0);
        Student student2=new Student(18,"李四",97.9);
        //if(student1.compareTo(student2)>0)返回1;根据下面的方法进行进一步的返回
        System.out.println(student1.compareTo(student2));
    }
    public static void main(String[] args) {
        Student []student=new Student[3];
        student[0]=new Student(36,"zhangsan",98.0);
        student[1]=new Student(18,"lisi",97.9);
        student[2]=new Student(27,"wangwu",65.3);
        System.out.println(Arrays.toString(student));
        Arrays.sort(student);
        System.out.println(Arrays.toString(student));
    }
     public static void main1(String[] args) {
         int []array=new int []{2,5,3,6,8};
         System.out.println(Arrays.toString(array));
         Arrays.sort(array);
         System.out.println(Arrays.toString(array));


     }

    @Override
//谁调用这个方法,谁就是this
    public int compareTo(Student o) {
    //return this.age-o.age;
    return o.name.compareTo(this.name);
    }
}

1.2Comparator interface

① Implement the operation of the Comparable interface:

②Comparison of names implemented through this interface:

③ ascending descending order

Result after execution: 

④Advantages

Flexible, not strong inclination to classes 

⑤ The overall code is as follows:

import java.util.Arrays;
import java.util.Comparator;
class Student {
    public int age;
    public String name;
    public double score;
    public Student(int age, String name, double score) {
        this.age = age;
        this.name = name;
        this.score = score;
    }
    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", score=" + score +
                '}';
    }
}
class AgeComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.age-o2.age;
    }
}
class ScoreComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return (int)(o1.score-o2.score);
    }
}
class NameComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.name.compareTo(o2.name);
    }
}
public class Test {
    public static void main2(String[] args) {
        Student students1 = new Student(1,"bit",98.9);
        Student students2 = new Student(2,"abc",88.9);
       /* if(students1.compareTo( students2) > 0) {
        }*/
        //System.out.println(students1.compareTo( students2));
        AgeComparator ageComparator = new AgeComparator();
        System.out.println(ageComparator.compare(students1,students2));
    }
    public static void main(String[] args) {
        Student[] student = new Student[3];
        student[0] = new Student(12,"lisi",98.9);
        student[1] = new Student(6,"zangwu",88.9);
        student[2] = new Student(18,"whangsan",18.9);
        System.out.println(Arrays.toString(student));
        AgeComparator ageComparator = new AgeComparator();
        ScoreComparator scoreComparator = new ScoreComparator();
        NameComparator nameComparator = new NameComparator();
        Arrays.sort(student,nameComparator);//默认是从小到大的排序
        System.out.println(Arrays.toString(student));
    }
    public static void main1(String[] args) {
        int[] array = {1,21,3,14,5,16};
        System.out.println(Arrays.toString(array));
        Arrays.sort(array);
        System.out.println(Arrays.toString(array));
    }
}

2. Cloneable interface

①How to implement the Cloneable interface:

There is a clone method in the Object class. Calling this method can create a " copy " of an object. However, in order to call the clone method legally , the Clonable interface must be implemented first , otherwise a CloneNotSupportedException will be thrown .

a. Implement the Cloneable interface

b. Override the Cloneable method

 c. throw exception, cast type

② Frequently asked questions in interviews:

Do you know the Cloneable interface? Why is it an empty interface and what does it do?

The empty interface, the flag interface, means that this class can be cloned

③ The schematic diagram of the clone:

④ Implementation of the overall code:

class Person implements Cloneable{
    public int age;
    public void eat(){
        System.out.println("吃!");
    }

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

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

public class TestDemo {



    public static void main(String[] args) throws CloneNotSupportedException {
        Person person = new Person();
        person.age=13;
        Person person2=(Person)person.clone();
        System.out.println(person2);
        System.out.println(person);
        System.out.println("===========");
        person2.age=14;
        System.out.println(person);
        System.out.println(person2);

    }
}

 

2.1 Deep copy and shallow copy

①Dark and shallow copy:

The decision to make a deep copy or a shallow copy is not the purpose of the method, but the implementation of the code

②Shallow copy example

 

The shallow copy code is as follows:

class Money implements Cloneable{
    public double m = 12.5;
}
class Person implements Cloneable{
    public int age;
    public Money money = new Money();

    public void eat() {
        System.out.println("吃!");
    }

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

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person tmp = (Person)super.clone();
        return tmp;
    }
}
public class TestDemo {
    public static void main(String[] args) throws CloneNotSupportedException {
        Person person = new Person();
        Person person2 = (Person)person.clone();
        System.out.println(person.money.m);
        System.out.println(person2.money.m);
        System.out.println("=====================");
        person2.money.m = 98.5;
        System.out.println(person.money.m);
        System.out.println(person2.money.m);
    }
}

 ③Example of deep copy: (copy the money in tmp too)

The deep copy code is as follows:

class Money implements Cloneable{
    public double m = 12.5;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
class Person implements Cloneable{
    public int age;
    public Money money = new Money();

    public void eat() {
        System.out.println("吃!");
    }

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

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person tmp = (Person)super.clone();
        tmp.money = (Money) this.money.clone();
        return tmp;
        //return super.clone();
    }
}
public class TestDemo {

    public static void main(String[] args) throws CloneNotSupportedException {
        Person person = new Person();
        Person person2 = (Person)person.clone();
        System.out.println(person.money.m);
        System.out.println(person2.money.m);
        System.out.println("=====================");
        person2.money.m = 98.5;
        System.out.println(person.money.m);
        System.out.println(person2.money.m);
    }
}

Thanks for watching~~~(* ̄︶ ̄)

Guess you like

Origin blog.csdn.net/weixin_58850105/article/details/123438815