Java self - Collections Framework Comparator and Comparable

Java Comparator和Comparable

Step 1: Comparator

Hero assume there are three attributes name, hp, damage
in a set place to store 10 Hero, sort through these 10 Collections.sort
So in the end hp small place in front of? Or damage small place in front of ? Collections.sort can not be sure
it is specified in the end to be sorted according to what kind of property
here will need to provide a Comparator given how between the two objects the size comparison
Comparator

//Hero.java
package charactor;
  
public class Hero  {
    public String name;
    public float hp;
  
    public int damage;
  
    public Hero() {
  
    }
  
    public Hero(String name) {
 
        this.name = name;
    }
  
    public String toString() {
        return "Hero [name=" + name + ", hp=" + hp + ", damage=" + damage + "]\r\n";
    }
 
    public Hero(String name, int hp, int damage) {
        this.name = name;
        this.hp = hp;
        this.damage = damage;
    }
  
}
 //TestCollection.java
package collection;
     
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
    
import charactor.Hero;
     
public class TestCollection {
    public static void main(String[] args) {
        Random r =new Random();
        List<Hero> heros = new ArrayList<Hero>();
            
        for (int i = 0; i < 10; i++) {
            //通过随机值实例化hero的hp和damage
            heros.add(new Hero("hero "+ i, r.nextInt(100), r.nextInt(100)));
        }
        System.out.println("初始化后的集合:");
        System.out.println(heros);
            
        //直接调用sort会出现编译错误,因为Hero有各种属性
        //到底按照哪种属性进行比较,Collections也不知道,不确定,所以没法排
        //Collections.sort(heros);
            
        //引入Comparator,指定比较的算法
        Comparator<Hero> c = new Comparator<Hero>() {
            @Override
            public int compare(Hero h1, Hero h2) {
                //按照hp进行排序
                if(h1.hp>=h2.hp)
                    return 1;  //正数表示h1比h2要大
                else
                    return -1;
            }
        };
        Collections.sort(heros,c);
        System.out.println("按照血量排序后的集合:");
        System.out.println(heros);
    }
}

Step 2: the Comparable

Hero class that implements the Comparable interface
provided in the class comparison algorithm inside
Collections.sort have enough information to sort, and there is no need to provide additional comparator Comparator
Note : If -1 is returned, it indicates that the current is smaller, otherwise larger

Comparable

package charactor;
    
public class Hero implements Comparable<Hero>{
    public String name;
    public float hp;
       
    public int damage;
       
    public Hero(){
          
    }
      
    public Hero(String name) {
        this.name =name;
  
    }
      
    //初始化name,hp,damage的构造方法
    public Hero(String name,float hp, int damage) {
        this.name =name;
        this.hp = hp;
        this.damage = damage;
    }
  
    @Override
    public int compareTo(Hero anotherHero) {
        if(damage<anotherHero.damage)
            return 1; 
        else
            return -1;
    }
  
    @Override
    public String toString() {
        return "Hero [name=" + name + ", hp=" + hp + ", damage=" + damage + "]\r\n";
    }
      
}
package collection;
   
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
  
import charactor.Hero;
   
public class TestCollection {
    public static void main(String[] args) {
        Random r =new Random();
        List<Hero> heros = new ArrayList<Hero>();
          
        for (int i = 0; i < 10; i++) {
            //通过随机值实例化hero的hp和damage
            heros.add(new Hero("hero "+ i, r.nextInt(100), r.nextInt(100)));
        }
          
        System.out.println("初始化后的集合");
        System.out.println(heros);
          
        //Hero类实现了接口Comparable,即自带比较信息。
        //Collections直接进行排序,无需额外的Comparator
        Collections.sort(heros);
        System.out.println("按照伤害高低排序后的集合");
        System.out.println(heros);
          
    }
}

Exercise : Custom order TreeSet

By default, data TreeSet is small to large order, but the constructor TreeSet support to pass in a Comparator

public TreeSet(Comparator comparator) 

Create a TreeSet by this construction method, which makes the sort of numbers are down

Answer:

package collection;
 
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
 
public class TestCollection {
    public static void main(String[] args) {
         
        Comparator<Integer> c =new Comparator<Integer>() {
 
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2-o1;
            }
        };
         
        Set<Integer> treeSet = new TreeSet<>(c);
        for (int i = 0; i < 10; i++) {
            treeSet.add(i);
        }
        System.out.println(treeSet);
    }
}

Guess you like

Origin www.cnblogs.com/jeddzd/p/12158419.html