Implement Comparable interface and Comparator interface

Posted by five on Tue, 21 Dec 2021 17:51:32 +0100

Declare an Employee class, including number, name and salary, and implement the Comparable interface. It is required to compare the size according to the salary. If the salary is the same, compare the size according to the number.

Declare a test class TestEmployee class, create an Employee [] array in main, with a length of 5, and store 5 Employee objects. Now it is required to sort this array with bubble sorting to sort and traverse the results.

Exercise 1:

Declare an Employee class, including number, name and salary, and implement the Comparable interface. It is required to compare the size according to the salary. If the salary is the same, compare the size according to the number.

Declare a test class TestEmployee class, create an Employee [] array in main, with a length of 5, and store 5 Employee objects. Now it is required to sort this array with bubble sorting to sort and traverse the results.

public class Employee implements Comparable{
    private int id;
    private String name;
    private int salay;

    public Employee() {
    }

    public Employee(int id, String name, int salay) {
        this.id = id;
        this.name = name;
        this.salay = salay;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getSalay() {
        return salay;
    }

    public void setSalay(int salay) {
        this.salay = salay;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", salay=" + salay +
                '}';
    }

    @Override
    public int compareTo(Object o) {
        Employee ee = (Employee) o;
        if(this.salay != ee.salay){
            return this.salay - ee.salay;
        }else{
//            if(this.id > ee.id)
            return this.id - ee.id;
        }
    }
}

Test class:

package ed.hfuu.interface1;

import java.util.Arrays;

public class TestEE {
    public static void main(String[] args) {
        Employee[] employees = new Employee[5];

        employees[0] = new Employee(1, "abc", 10000);
        employees[1] = new Employee(2, "abc", 100);
        employees[2] = new Employee(3, "abc", 1000);
        employees[3] = new Employee(4, "abc", 10000);
        employees[4] = new Employee(5, "abc", 1000000);

        for(int i = 0; i < employees.length - 1; i++){
            for(int j = 0; j < employees.length - 1 - i; j++){
                if(employees[j].compareTo(employees[j + 1]) > 0){
                    Employee eeTemp = employees[j];
                    employees[j] = employees[j + 1];
                    employees[j + 1] = eeTemp;
                }
            }
        }

        for (Employee employee : employees) {
            System.out.println(employee.toString());
        }

    }
}
Exercise 2: customize the array sorting tool class

Customize an array tool class MyArrays, which contains a static method that can sort arbitrary object arrays from small to large by bubble sorting. How do you define this method?
Note: here, the array element object must implement the comparable interface, otherwise ClassCastException will occur. The Employee class tested here implements the comparable interface (as in the above example).

class MyArrays{
	public static void sort(Object[] arr){
		//Bubble sorting
		for (int i = 1; i < arr.length; i++) {
			for (int j = 0; j < arr.length-i; j++) {
				//The purpose of forcing arr[j] to the Comparable interface type is to call the compareTo method
				//Of course, if the elements of the array do not implement this interface, ClassCastException will occur
				Comparable c = (Comparable) arr[j];
				if(c.compareTo(arr[j+1])>0){
					Object temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}
			}
		}
	}
}

java. util. This is how the public static void sort(Object[] a) of the arrays tool class is implemented, but the sorting algorithm it uses is more efficient and faster, rather than bubble sorting. However, no matter which sorting algorithm involves the comparison size of two elements, it needs to call the compareTo() method through the element.

reflection:

(1) If a class does not implement the Comparable interface, and it is inconvenient for you to modify this class (for example, for some third-party classes, you only have. Class files and no source files), what should you do if the objects of this class also have to be compared in size?

(2) If a class implements the Comparable interface and specifies the rules for comparing the sizes of two objects, but at this moment I don't want to compare the sizes according to its predefined methods, but I can't modify it at will, because it will affect the use in other places, what should I do?

At the beginning of designing the class library, JDK also considered this situation, so it added a Java util. Comparator interface.

package java.util;

public interface Comparator{
    int compare(Object o1,Object o2);
}

So how do we compare the sizes of two objects of a class? Steps:

Step 1: write a class, which we call comparator type, to implement Java util. Comparator interface and override the method

  • The method body is how you specify the size of the two objects

Step 2: when comparing the size, call the compare() method through the object of the comparator type, pass in the two objects to be compared as the arguments of the compare method, and decide who is big and who is small according to the return value of the method.

  • o1 object greater than o2 returns a positive integer
  • o1 object less than o2 returns a negative integer
  • The o1 object equals o2 and returns zero

Code example: a student class that does not implement the Comparable interface

class Student{
	private String name;
	private int score;
	public Student(String name, int score) {
		super();
		this.name = name;
		this.score = score;
	}
	public Student() {
		super();
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getScore() {
		return score;
	}
	public void setScore(int score) {
		this.score = score;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", score=" + score + "]";
	}
	
}

Code example: defining a custom comparator class

class StudentScoreCompare implements Comparator{

	@Override
	public int compare(Object o1, Object o2) {
		Student s1 = (Student) o1;
		Student s2 = (Student) o2;
		return s1.getScore() - s2.getScore();
	}
	
}

Code example: test class

import java.util.Comparator;

public class TestComparator {
	public static void main(String[] args) {
		Student stu1 = new Student("Zhang San",89);
		Student stu2 = new Student("Li Si",78);
		
		StudentScoreCompare ssc = new StudentScoreCompare();
		if(ssc.compare(stu1, stu2)>0){
			System.out.println(stu1 + ">" + stu2);
		}else if(ssc.compare(stu1, stu2)<0){
			System.out.println(stu1 + "<" + stu2);
		}else{
			System.out.println(stu1 + "=" + stu2);
		}
	}
}
Exercise 1: bubble sorting

Declare an Employee class, including number, name, salary,

Declare a test class. In main, create an Employee [] array with a length of 5 to display the original sequence results

Declare a custom Comparator EmpSalaryComparator, implement the Comparator interface, and compare the size according to salary

Declare a custom Comparator EmpIdComparator, implement the Comparator interface, and compare the size according to the number

In the test class, use the two comparator objects to sort the array and display the sorted results

Employee class example code:

class Employee{
	private int id;
	private String name;
	private double salary;
	public Employee(int id, String name, double salary) {
		super();
		this.id = id;
		this.name = name;
		this.salary = salary;
	}
	public Employee() {
		super();
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + "]";
	}
}

Employee salary custom comparator type:

class EmpSalaryComparator implements Comparator{

	@Override
	public int compare(Object o1, Object o2) {
		Employee e1 = (Employee) o1;
		Employee e2 = (Employee) o2;
		return Double.compare(e1.getSalary(), e2.getSalary());
	}
	
}

Employee number custom comparator type:

class EmpIdComparator implements Comparator{

	@Override
	public int compare(Object o1, Object o2) {
		Employee e1 = (Employee) o1;
		Employee e2 = (Employee) o2;
		return e1.getId() - e2.getId();
	}
	
}

Test class example code:

import java.util.Comparator;

public class TestComparator {
	public static void main(String[] args) {
		Employee[] arr = new Employee[5];
		arr[0] = new Employee(1,"Zhang San",13000);
		arr[1] = new Employee(3,"Wang Wu",14000);
		arr[2] = new Employee(2,"Li Si",13000);
		arr[3] = new Employee(4,"Zhao Liu",7000);
		arr[4] = new Employee(5,"Qian Qi",9000);
		
		//Original sequence
		System.out.println("Employee list:");
		for (int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);
		}
		
		EmpSalaryComparator ec = new EmpSalaryComparator();
		//Bubble sorting
		for (int i = 1; i < arr.length; i++) {
			for (int j = 0; j < arr.length-i; j++) {
				if(ec.compare(arr[j], arr[j+1])>0){
					Employee temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}
			}
		}
		
		System.out.println("Employee list sorted by salary:");
		for (int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);
		}
		
		EmpIdComparator ec2 = new EmpIdComparator();
		//Bubble sorting
		for (int i = 1; i < arr.length; i++) {
			for (int j = 0; j < arr.length-i; j++) {
				if(ec2.compare(arr[j], arr[j+1])>0){
					Employee temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}
			}
		}
				
		System.out.println("List of employees sorted by number:");
		for (int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);
		}
	}
}
Exercise 2: customize the array sorting tool class

Customize an array tool class MyArrays, which contains a static method that can sort arbitrary object arrays from small to large by bubble sorting. How do you define this method?

class MyArrays{
	public static void sort(Object[] arr,Comparator c){
		//Bubble sorting
		for (int i = 1; i < arr.length; i++) {
			for (int j = 0; j < arr.length-i; j++) {
				//No cast is required here
				if(c.compare(arr[j], arr[j+1])>0){
					Object temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}
			}
		}
	}
	
}

Simplify the code of exercise 1 test class with the new tool class

public class TestComparator {
	public static void main(String[] args) {
		Employee[] arr = new Employee[5];
		arr[0] = new Employee(1,"Zhang San",13000);
		arr[1] = new Employee(3,"Wang Wu",14000);
		arr[2] = new Employee(2,"Li Si",13000);
		arr[3] = new Employee(4,"Zhao Liu",7000);
		arr[4] = new Employee(5,"Qian Qi",9000);
		
		//Original sequence
		System.out.println("Employee list:");
		for (int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);
		}
		
		EmpSalaryComparator ec = new EmpSalaryComparator();
		MyArrays.sort(arr, ec);
		
		System.out.println("Employee list sorted by salary:");
		for (int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);
		}
		
		EmpIdComparator ec2 = new EmpIdComparator();
		MyArrays.sort(arr, ec2);
				
		System.out.println("List of employees sorted by number:");
		for (int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);
		}
	}
}

java. util. This is what the public static void sort (t [] A, comparator <? Super T > C) of the arrays tool class does