六、容器Treeset排序

一、Hashset元素必须重写hashcode和equals方法。Treeset容器排序是0即可判断。另外,在添加数据时排序,数据更改不会影响原来的顺序,不要修改数据,否则可能重复。treemap同理。

package mypro02;

public class Workers implements Comparable<Workers>{
    private String name;
    private int salary;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
    public Workers(String name, int salary) {
        super();
        this.name = name;
        this.salary = salary;
    }
    public Workers() {
        super();
    }
    @Override
    public String toString() {
        return "工种:"+this.getName()+"工资:"+this.getSalary()+"\n";
    }
    @Override
    public int compareTo(Workers o) {
        
        return this.getSalary()-o.getSalary()>0?1:(this.getSalary()==o.getSalary()?0:-1);
    }
    
    
}
package mypro02;

import java.util.TreeSet;

public class WorkersDemo01 {

    public static void main(String[] args) {
        
            
            Workers wk1=new Workers("教师",200);
            Workers wk2=new Workers("工人",2000);
            Workers wk3=new Workers("白领",1000);
            
            TreeSet<Workers> treeset=new TreeSet<Workers>();
            
            treeset.add(wk1);
            treeset.add(wk3);
            treeset.add(wk2);
            
            System.out.println(treeset);
        }

    

}
结果:[工种:教师工资:200
, 工种:白领工资:1000
, 工种:工人工资:2000
]

=================================================

package mypro02;

public class Person {
    private final String name;
    private final int  handsome;
    public Person(String name, int handsome) {
        super();
        this.name = name;
        this.handsome = handsome;
    }
    public Person() {
        this.name = "null";
        this.handsome = 0;
    }
    public String getName() {
        return name;
    }
    
    public int getHandsome() {
        return handsome;
    }
    
    @Override
    public String toString() {
        return "姓名:"+this.getName()+"帅气值:"+this.getHandsome()+"\n";
    }
    
    
}
package mypro02;

import java.util.Comparator;
import java.util.TreeSet;

class TreeSetDemo01 {
    public static  void main(String[] args) {
        Person p1=new Person("赵六",100);
        Person p2=new Person("张三",120);
        Person p3=new Person("李四",33);
        
        TreeSet<Person>  tr=new TreeSet<Person>(new Comparator<Person>() {

            @Override
            public int compare(Person o1, Person o2) {
                // TODO Auto-generated method stub
                return o1.getHandsome()-o2.getHandsome()>0?1:(o1.getHandsome()-o2.getHandsome()==0)?0:-1;
            }
        });
        tr.add(p1);
        tr.add(p2);
        tr.add(p3);
        System.out.println(tr);
    }
    
 }
结果:[姓名:李四帅气值:33
, 姓名:赵六帅气值:100
, 姓名:张三帅气值:120
]

 

posted @ 2022-03-27 19:46  小熊尤里  阅读(29)  评论(0编辑  收藏  举报