Home  >  Article  >  Java  >  Sorting of Java Basics TreeSet and Java Custom Types

Sorting of Java Basics TreeSet and Java Custom Types

coldplay.xixi
coldplay.xixiforward
2021-03-05 09:54:002980browse

Sorting of Java Basics TreeSet and Java Custom Types

TreeSet and Java custom type sorting

  • Demonstrates that TreeSet can sort String
  • TreeSet Unable to sort custom types
  • How to write comparison rules
  • Self-balancing binary tree structure
  • Implementing the comparator interface
  • Collections tool class

(Free learning recommendation: java basic tutorial)

Demonstrates TreeSet pairing String is sortable

1. The bottom layer of the TreeMap collection is actually a TreeMap
2. The bottom layer of the TreeMap collection is a binary tree
3. The elements placed in the TreeSet collection , which is equivalent to being placed in the key part of the TreeMap collection.
4. The elements in the TreeSet collection are unordered and cannot be repeated, but they can be automatically sorted according to the size of the elements.

is called: a sortable collection
For example: write a program to retrieve data from the database, and display user information on the page in ascending or descending order by birthday.
You can use the TreeSet collection at this time, because the TreeSet collection is put in and taken out in order. of.

//创建一个TreeSet集合
  TreeSet<string> ts=new TreeSet();
  //添加Stringts.add("zhangsan");ts.add("lisi");ts.add("wangwu");ts.add("zhangsi");ts.add("wangliu");for(String s:ts){
      //按照字典顺序排序
      System.out.print(s+" ");
  }
  TreeSet<integer> ts2=new TreeSet();ts2.add(100);ts2.add(200);ts2.add(900);ts2.add(800);  ts2.add(600);ts2.add(10);for(Integer i:ts2){
      //按照升序排序
      System.out.print(i+" ");}</integer></string>

Sorting of Java Basics TreeSet and Java Custom Types

TreeSet cannot sort custom types

Can TreeSet sort custom types?
In the following program, the Person class cannot be sorted because the comparison rules between Person objects are not specified. It is not stated who is older and who is younger.

public class TreeSetTest02 {
    public static void main(String[] args) {
        Person p1=new Person(50);
        Person p2=new Person(10);
        Person p3=new Person(20);
        Person p4=new Person(60);
        Person p5=new Person(40);
        Person p6=new Person(30);
        TreeSet<person> persons=new TreeSet();
        persons.add(p1);
        persons.add(p2);
        persons.add(p3);
        persons.add(p4);
        persons.add(p5);
        persons.add(p6);
        for(Person p:persons){
            System.out.println(p);
        }
    }}class Person{
    int age;
    public Person(int age){
        this.age=age;
    }
    @Override
    public String toString() {
        return "Person [age=" + age + "]";
    }}</person>
Exception in thread "main" java.lang.ClassCastException: testCollection.Person cannot be cast to java.lang.Comparable

The reason for this error is that the
Person class does not implement the java.lang, Comparable interface

//Put it in the TreeSet collection The elements in need to implement the java.lang.Comparable interface
//And implement the compareTo method, equals does not need to be written

  public class TreeSetTest04 {
        public static void main(String[] args) {
            Customer p1=new Customer(50);
            Customer p2=new Customer(10);
            Customer p3=new Customer(20);
            Customer p4=new Customer(60);
            Customer p5=new Customer(40);
            Customer p6=new Customer(30);
            TreeSet<customer> customers=new TreeSet();
            customers.add(p1);
            customers.add(p2);
            customers.add(p3);
            customers.add(p4);
            customers.add(p5);
            customers.add(p6);
            for(Customer p:customers){
                System.out.println(p);
            }
        }
    }
    //放在TreeSet集合中的元素需要实现java.lang.Comparable接口//并且实现compareTo方法,equals可以不写
    class Customer implements Comparable<customer>{
        int age;
        public Customer(int age){
            this.age=age;
        }
        @Override
        public String toString() {
            return "Customer [age=" + age + "]";
        }
        //需要在这个方法中编写比较的逻辑,或者说比较的规则,按照什么进行比较。
        //k.compareTo(t.key)
        //拿着参数k和集合中的每个k进行比较,返回值可能是>0,age2){//       return 1;//    }else{//       return -1;//    }
            return this.age-c.age;    //>,<p>//You need to write the comparison logic in this method, or compare The rules according to which comparisons are made. <br> //k.compareTo(t.key)<br> //Compare parameter k with each k in the set. The return value may be >0, / /<strong>Comparison rules are ultimately implemented by programmers: for example, in ascending order by age, or in descending order by age</strong></p>
<p><strong>How to write comparison rules</strong></p>
<p>First sort by age Ascending order, if the age is the same, then order by name in ascending order </p>
<pre class="brush:php;toolbar:false">public class TreeSetTest05 {
    public static void main(String[] args) {
        TreeSet<vip> vips=new TreeSet();
        vips.add(new Vip("zhangsi",20));
        vips.add(new Vip("zhangsan",20));
        vips.add(new Vip("king",18));
        vips.add(new Vip("soft",17));
        for(Vip vip:vips){
            System.out.println(vip);
        }
    }}class Vip implements Comparable<vip>{
    String name;
    int age;
    public Vip(String name,int age){
        this.name=name;
        this.age=age;
    }
    @Override
    public String toString() {
        return "Vip [name=" + name + ", age=" + age + "]";
    }
    //compareTo方法的返回值很重要:
    //返回0表示相同,value会覆盖
    //>0,会继续在右子树上找
    //<p><strong>Self-balancing binary tree structure</strong></p>
<p>1.<strong>Self-balancing binary tree, follow the principle of small left and large right </strong><br> 2. There are three ways to traverse a binary tree <br> Pre-order traversal: left and right roots <br> In-order traversal: left and right roots <br> Post-order traversal: left and right roots <br> Note: front and center What I will talk about later is the location of the root<br> 3.<strong>TreeSet collection and TreeMap collection use in-order traversal, that is, left root and right. They are self-balancing binary trees</strong><br> 100 200 50 60 80 120 140 130 135 180 666</p>
<p><strong>Implement the comparator interface</strong></p>
<p>The elements in the TreeSet collection can be sorted The second way is to use a comparator</p>
<pre class="brush:php;toolbar:false">public class TreeSetTest06 {
    public static void main(String[] args) {
        //创建TreeSet集合的时候,需要使用比较器
        //TreeSet<wugui> wuGuis=new TreeSet();   //这样不行,没有通过构造方法传递一个比较器进去
        TreeSet<wugui> wuGuis=new TreeSet(new WuguiComparator());
        wuGuis.add(new Wugui(1000));
        wuGuis.add(new Wugui(800));
        wuGuis.add(new Wugui(900));
        wuGuis.add(new Wugui(300));
        wuGuis.add(new Wugui(60));
        for(Wugui wugui:wuGuis){
            System.out.println(wugui);
        }

    }}class Wugui{
    int age;

    public Wugui(int age) {
        super();
        this.age = age;
    }

    @Override
    public String toString() {
        return "Wugui [age=" + age + "]";
    }}//单独再这里编写一个比较器//比较器实现java.util.Comparator接口(Comparable是java.lang包下的)class WuguiComparator implements Comparator<wugui>{
    public int compare(Wugui o1,Wugui o2){
        //指定比较规则
        //按照年龄排序
        return o1.age-o2.age;
    }}</wugui></wugui></wugui>

Sorting of Java Basics TreeSet and Java Custom Types
We can use the anonymous inner class method
We can use the anonymous inner class method (this class has no name , direct new interface)

TreeSet<wugui> wuGuis=new TreeSet(new Comparator<wugui>(){public int compare(Wugui o1,Wugui o2){
        //指定比较规则
        //按照年龄排序
        return o1.age-o2.age;
        }});</wugui></wugui>

Final conclusion, if you want to sort the elements placed in the key part of the TreeSet or TreeMap collection, there are two ways
The first one: put The elements in the collection implement the java.lang.Comparable interface
The second method: pass a comparator object to it when constructing the TreeSet or TreeMap collection.

How to choose between Comparable and Comparator?
When the comparison rules will not change, or when there is only one comparison rule, it is recommended to implement the Comparable interface
If there are multiple comparison rules and multiple comparison rules are needed For frequent switching between comparison rules, it is recommended to use the comparator interface
The design of the comparator interface complies with OCP principles.

Collections tool class

java.util.Collections collection tool class, which facilitates the operation of collections

public class CollectionsTest {
    static class Wugui2 implements Comparable<wugui2>{
        int age;

        public Wugui2(int age) {
            super();
            this.age = age;
        }

        @Override
        public String toString() {
            return "Wugui2 [age=" + age + "]";
        }

        @Override
        public int compareTo(Wugui2 o) {
            // TODO Auto-generated method stub
            return this.age-o.age;
        }
    }
    public static void main(String[] args) {
        //ArrayList集合不是线程安全的
        List<string> list=new ArrayList<string>();
        //变成线程安全的
        Collections.synchronizedList(list);
        //排序
        list.add("abc");
        list.add("abe");
        list.add("abd");
        list.add("abf");
        list.add("abn");
        list.add("abm");
        Collections.sort(list);
        for(String s:list){
            System.out.println(s);
        }
        List<wugui2> wuguis=new ArrayList();
        wuguis.add(new Wugui2(1000));
        wuguis.add(new Wugui2(8000));
        wuguis.add(new Wugui2(4000));
        wuguis.add(new Wugui2(6000));
        //注意:对list集合中元素排序,需要保证list集合中元素实现了Comparable接口
        Collections.sort(wuguis);
        for(Wugui2 wugui:wuguis){
            System.out.println(wugui);
        }
        //对set集合怎么排序呢
        Set<string> set=new HashSet();
        set.add("king");
        set.add("kingsoft");
        set.add("king2");
        set.add("king1");
        //将set集合转换成list集合
        List<string> myList=new ArrayList(set);
        Collections.sort(myList);
        for(String s:myList){
            System.out.println(s);
        }
        //这种方式也可以排序
        //Collections.sort(list集合,比较器对象)
    }}</string></string></wugui2></string></string></wugui2>

Sorting of Java Basics TreeSet and Java Custom Types

Related learning recommendations: java basics

The above is the detailed content of Sorting of Java Basics TreeSet and Java Custom Types. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete