The difference between Java and comparator of the compareable

I. Introduction contrast

Comparator interface compareable implement interface classes, object instances are sorted array for convenience because it can be called directly
java.util.Arrays.sort (object array name), you can be customized collation. Sort realization principle is based on red and black binary realization of the principle.

  • Comparable is the sort interface. If a class implements the Comparable interface, it means that the class supports sorting. List or array implements Comparable interface class objects can be automatically sorted by Collections.sort or Arrays.sort.
  • Comparator is more interfaces, if we need to control the order of a class, but the class itself does not support ordering (ie not implement the Comparable interface), then we can build a "class Comparator" to sort this "more It is "only needs to implement Comparator interface. In other words, we can create a comparator by implementing Comparator, and then sort through this kind of comparator.

Differences:
different methods implemented collation 1

  • Comparable interface methods: compareTo (Object o)

  • Comparator interface methods: compare (T o1, To2)

2 before and after the design of different types

  • Comparable interface for use in the design class; initial design, to achieve this excuse, the specified ordering.

  • Comparator interface design has been completed for the class, I would like to sort (Arrays).

Second, the example operation Comparable interface

N number of classes in both the compareTo method, the fundamental reason is because they have achieved comparable interfaces interfaces, and implements the interface compareTo method.

Compareable achieve the jdk source category
Here Insert Picture Description

Student class implement the Comparable interface is created, the override compareTo () method,

Results in descending order, by age equivalent score from small to large.

package ch11.lei.ji;
/*实现Comparator接口的类可以方便的排序,
 * 覆写compareTo接口
 * java.util.Arrays.sort(对象类数组),*/
class Student implements Comparable<Student> {    // 指定类型为Student
    private String name ;
    private int age ;
    private float score ;
    public Student(String name,int age,float score){
        this.name = name ;
        this.age = age ;
        this.score = score ;
    }
    public String toString(){
        return name + "\t\t" + this.age + "\t\t" + this.score ;
    }
    public int compareTo(Student stu){    // 覆写compareTo()方法,实现排序规则的应用
        if(this.score>stu.score){
            return -1 ;
        }else if(this.score<stu.score){
            return 1 ;
        }else{
            if(this.age>stu.age){
                return 1 ;
            }else if(this.age<stu.age){
                return -1 ;
            }else{
                return 0 ;
            }
        }    
    }
};
public class Comparable01{
    public static void main(String args[]){
        Student stu[] = {new Student("张三",20,90.0f),
            new Student("李四",22,90.0f),new Student("王五",20,99.0f),
            new Student("赵六",20,70.0f),new Student("孙七",22,100.0f)} ;
        java.util.Arrays.sort(stu) ;    // 进行排序操作
        for(int i=0;i<stu.length;i++){    // 循环输出数组中的内容
            System.out.println(stu[i]) ;
        }
    }
};

Three, Comparator interface instance operation

Student01 type not originally comparator, the comparator constructs a class after completion of class StudentComparator

By age descending order.

package ch11.lei.ji;
import java.util.* ;
 class Student01{    // 指定类型为Student
    private String name ;
    private int age ;
    public Student01(String name,int age){
        this.name = name ;
        this.age = age ;
    }
    public boolean equals(Object obj){    // 覆写equals方法
        if(this==obj){
            return true ;
        }
        if(!(obj instanceof Student)){
            return false ;
        }
        Student01 stu = (Student01) obj ;
        if(stu.name.equals(this.name)&&stu.age==this.age){
            return true ;
        }else{
            return false ;
        }
    }
    public void setName(String name){
        this.name = name ;
    }
    public void setAge(int age){
        this.age = age ;
    }
    public String getName(){
        return this.name ;
    }
    public int getAge(){
        return this.age ;
    }
    public String toString(){
        return name + "\t\t" + this.age  ;
    }
};

class StudentComparator implements Comparator<Student01>{    // 实现比较器
    // 因为Object类中本身已经有了equals()方法
    public int compare(Student01 s1,Student01 s2){
        if(s1.equals(s2)){
            return 0 ;
        }else if(s1.getAge()<s2.getAge()){    // 按年龄比较
            return 1 ;
        }else{
            return -1 ;
        }
    }
};

public class Comparator01{
    public static void main(String args[]){
        Student01 stu[] = {new Student01("张三",20),
            new Student01("李四",22),new Student01("王五",20),
            new Student01("赵六",20),new Student01("孙七",22)} ;
        java.util.Arrays.sort(stu,new StudentComparator()) ;    // 进行排序操作
        for(int i=0;i<stu.length;i++){    // 循环输出数组中的内容
            System.out.println(stu[i]) ;
        }
    }
};

Note: 1, if a class to implement Comparator interface: it must be achieved compare (T o1, T o2) function, but may not be implemented equals (Object obj) function.

2, int compare (T o1, T o2) is "o1 and o2 of the magnitude comparison." Return to "negative", which means "o1 o2 than small"; return to "zero", meaning "o1 o2 equal"; return "positive", meaning "o1 is greater than o2."

Fourth, when the sorter is used to customize the time

Such as: Collections.sort the need to pass a custom sequencer, use anonymous inner classes, incoming Comparator, rewriting method, the way to sort A.compareToB

    static void sortByValue(Map map) {
        List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });
        for (Map.Entry<String, Integer> mapping : list) {
            System.out.println("键:" + mapping.getKey() + " 值:" + mapping.getValue());
        }

Note: Here o1.getValue().compareTo(o2.getValue())is the string itself to achieve a method of comparing the
interface to achieve the String class
public final class String extends Object implements Serializable, Comparable<String>, CharSequence

Five, Comparable and Comparator compare the difference

Comparable is ordering interfaces, if a class implements the Comparable interface, it means "This class supports sorting." The Comparator is a comparator, if we need to control the order of a class, you can create a "class Comparator" to sort.

Comparable corresponds to the "internal comparator 'Comparator and corresponds to the" external comparator. "

Both methods have advantages and disadvantages, with Comparable simple, as long as the object implement Comparable interface object can be directly compared, but the need to modify the source code. Comparator with advantage without modifying the source code, but to achieve a further comparator, when a need for custom objects for comparison, together with the comparator and pass the object than in the past on the size, and the inside Comparator users can implement their own complex logic can be generic so that it can match some of the more simple objects, so you can save a lot of duplication of effort.

Sixth, expand: a collection of TreeSet (natural ordering and custom sorting)

A, TreeSet natural ordering:

step:

1. Let the element itself has a comparative,

2. Compareable implement an interface, covering CompareTo method

Example:

Class Student  implements Comparable//第一:实现Compareable接口

{

private String   name;

private int age;


 //复写构造函数初始化姓名跟年龄


Student(String name,int age)

{

   this.name = name;

   this.age = age;

}


public int compareTo(Object obj) //第二:复写CompareTo方法

{
 
   //return 0;

   if(!(objinstanceof Student))   //第三:判断对象是否是特定类的一个实例

       throw new RuntimeException("不是学生对象");

   Student s = (Student)obj;

   System.out.println(this.name+"....compareto....."+s.name);


//第四:当前对象的年龄与插入对象的年龄进行比较,当前年龄大于插入对象的年龄时,返回1,

此时将插入二叉树的右边,当等于时,返回0,进行次要条件的比较,再次调用;当小于时,返回-1;


   if(this.age>s.age)     //判断当前对象年龄是否大于传入的对象年龄

       return 1;

   if(this.age==s.age)     //如果当前年龄等于传入对象的年龄,则比较姓名是否相同

   {

       return this.name.compareTo(s.name);

   }

   return -1;

   /**/

}


public String getName()   //获取姓名

{
   return  name;
}
public int getAge()    //获取年龄
{
   return  age;
}
}
 
Class TreeSetDemo

{

public static void main(String[] args)

{

   TreeSet ts = newTreeSet();   //创建一个TreeSet的集合

   ts.add(new Student("lisi02",22));      //往集合添加元素

   ts.add(new Student("lisi007",20));

   ts.add(new Student("lisi09",19));

   ts.add(new Student("lisi08",19));


   Iterator it = ts.iterator();  //初始化迭代器,遍历集合中的所有元素

   while(it.hasNext())

   {

       Student stu = (Student)it.next();

       System.out.println(stu.getName()+"..."+stu.getAge());

   }

}

}

Two, TreeSet custom sorting

1, Origin: When the comparative element itself does not have, or have not required comparative.
Then we should let the set itself has a comparative, at initialization, there is a comparison mode.

2, steps:

1) implement a comparator

2) compare replication method

3) When you create a TreeSet collection of objects, providing a a Comparator object,

Example:

import java.util.Comparator;

import java.util.Set;

import java.util.TreeSet;

Class Student1{

private Integer age;

public Student1(Integer age) {

   super();

   this.age = age;

}

public Integer getAge() {

   return age;

}

public void setAge(Integer age) {

   this.age = age;

}

@Override

public String toString() {

   return age + "";
}

}

 
 

class MyComparator implements Comparator{  //第一步:实现Comparator接口


@Override

public int compare(Object o1, Object o2) {   //第二步:实现一个campare方法

//判断对象是否是特定类的一个实例


   if(o1 instanceof Student1 & o2instanceof Student1){

       Student1 s1 =(Student1)o1;

       Student1 s2 =(Student1)o2;

       if(s1.getAge() > s2.getAge()){

          return -1;

       }else if(s1.getAge() < s2.getAge()){

          return 1;

       }

   }

   return 0;

}

}

 

public Class Demo15 {


public static void main(String[] args) {

   Set<Student1> s= new TreeSet(new  MyComparator());//第三步:创建TreeSet集合对象时,提供一个一个Comparator对象,

   /**

    * 要实现定制排序,需要在创建TreeSet集合对象时,提供一个一个Comparator对象,

    * 该对象里负责集合元素的排序逻辑;

    */

   s.add(new Student1(140));

   s.add(new Student1(15));

   s.add(new Student1(11));

   s.add(new Student1(63));

   s.add(new Student1(96));

   System.out.println(s);

}


}

Reference article:
https://blog.csdn.net/wilson27/article/details/90339765
https://www.cnblogs.com/xujian2014/p/5215082.html
https://blog.csdn.net/liuchuangjin/article / details / 46500283

Published 107 original articles · won praise 14 · views 40000 +

Guess you like

Origin blog.csdn.net/belongtocode/article/details/102930203