Common Java classes - comparison classes

Keywords: Java IDEA

Comparison class

introduce

  • Under normal circumstances, objects in Java can only be compared: = = or! =, Comparison of > or < is not possible.

However, in the development scenario, we need to sort multiple objects, that is, we need to compare the size of objects.

How to implement: you need either of the two interfaces: Comparable or Comparator

1, Comparable interface

  1. Natural sorting
    • For example, String and wrapper classes implement the Comparable interface, rewrite the compareTo() method, and give a way to compare the sizes of two objects from small to large.
    • The list of objects (and arrays) that implement the Comparable interface can be sorted automatically through Collections.sort or Arrays.sort.
        @Test
        public void test(){
            String[] str = new String[]{"CC","JJ","MM","DD","GG"};
            Arrays.sort(str);
            System.out.println(Arrays.toString(str));
            // [CC, DD, GG, JJ, MM]
        }
    
  2. Rule to override compareTo():

    ① If the current object this is greater than the formal parameter object obj, a positive integer is returned;

    ② If the current object this is less than the formal parameter object obj, a negative integer is returned;

    ③ If the current object this is equal to the parameter object obj, 0 is returned

  3. For custom classes, if sorting is required, we can let the custom class implement the Comparable interface and override

    compareTo (Object obj) method, in which how to sort

    public class CompareTest {
       @Test
        public void test2(){
            Goods[] str = new Goods[5];
            str[0] = new Goods("lenovo",19);
            str[1] = new Goods("huawei",69);
            str[2] = new Goods("xiaomi",49);
            str[3] = new Goods("huawei",99);
            str[4] = new Goods("dell",99);
            Arrays.sort(str);
            System.out.println(Arrays.toString(str));
            // [{name='lenovo', price=19.0}, {name='xiaomi', price=49.0}, {name='huawei', price=69.0},
            // {name='dell', price=99.0}, {name='huawei', price=99.0}]      
    
        }
    }
    class Goods implements Comparable{
        private String name;
        private double price;
    
        public Goods() {
        }
        public Goods(String name, double price){
            this.name = name;
            this.price = price;
        }
    
    
        @Override
        public String toString() {
            return "{" +
                    "name='" + name + '\'' +
                    ", price=" + price +
                    '}';
        }
    
        @Override
        public int compareTo(Object o) {
            System.out.println("-----------------");
            if (o instanceof Goods){
                Goods goods = (Goods)o;
                if (this.price > goods.price)
                    return 1;
                else if(this.price < goods.price)
                    return -1;
                else
                    return this.name.compareTo(goods.name);//The name attribute is also ranked
            }
            throw new RuntimeException("The data type passed in is incorrect");
        }
    }
    
    

2, Comparator interface - custom sorting

  1. background

    When the element type does not implement the java.lang.Comparable interface and it is inconvenient to modify the code, or the sorting rules that implement the java.lang.Comparable interface are not suitable for the current amount operation, you can consider sorting with the Comparator object to force the overall sorting comparison of multiple objects

  2. Rewrite the compare (object o1, object o2) method to compare the sizes of o1 and o2
    • If a positive integer is returned, O1 > O2
    • If a negative integer is returned, O1 < O2
    • If 0 is returned, it indicates equality
```java
@Test
    public void test3(){
        Goods[] str1 = new Goods[6];
        str1[0] = new Goods("lenovo",18);
        str1[1] = new Goods("huawei",68);
        str1[2] = new Goods("xiaomi",48);
        str1[3] = new Goods("huawei",98);
        str1[4] = new Goods("dell",98);
        str1[5] = new Goods("oppo",298);
        Arrays.sort(str1, new Comparator() {
    @Override
        public int compare(Object o1, Object o2) {           
            if (o1 instanceof Goods && o2 instanceof Goods){
                Goods g1 = (Goods) o1;
                Goods g2 = (Goods) o2;
                //From big to small by name
                if (g1.getName().equals(g2.getName())){
                    return -Double.compare(g1.getPrice(),g2.getPrice());
                }else
                    return -g1.getName().compareTo(g2.getName());
                }
            throw new RuntimeException("Abnormal input data structure");
            }
        });        
        System.out.println(Arrays.toString(str1));
        // [{name='xiaomi', price=48.0}, {name='oppo', price=298.0}, {name='lenovo', price=18.0}, 
        // {name='huawei', price=98.0}, {name='huawei', price=68.0}, {name='dell', price=98.0}]
        
    }
```

3, Compare

  • Once the method of the Comparable interface is determined, ensure that the object of the implementation class of the Comparable interface can be compared in size at any position
  • The Comparator interface is a temporary comparison

Posted by buckboru on Thu, 18 Nov 2021 08:27:24 -0800