演示TreeSet對String可排序

演示TreeSet對String可排序

package com.lichennan.collection.map;

import java.util.TreeSet;

/*
 1.TreeSet集合底層實際上是一個TreeMap
 2.TreeMap集合底層是一個二叉樹。
 3.放到TreeSet集合中的元素,等同於放到TreeMap集合key部分了。
 4.TreeSet集合中的元素中的元素:無序不可重複,但是可以按照元素的大小順序自動排序。
 稱爲可排序集合。
 */
public class TreeSetTest021 {
    public static void main(String[] args) {
        TreeSet<String> ts = new TreeSet<>();
        ts.add("zhangsan");
        ts.add("lisi");
        ts.add("wangwu");
        ts.add("maliu");
        ts.add("alibaba");

        for (String s:ts) {
            System.out.println(s);
        }
    }

}

在這裏插入圖片描述

對自定義類型不可排序

package com.lichennan.collection.map;

import java.util.TreeSet;

/*
   對自定義的類型來說,TreeSet不可排序
   以下程序出現異常com.lichennan.collection.map.Person cannot be cast to java.lang.Comparable
 */
public class TreeSetTest03 {
    public static void main(String[] args) {
        Person p1 = new Person(23);
        Person p2 = new Person(83);
        Person p3 = new Person(43);
        Person p4 = new Person(23);

        TreeSet<Person> persons = new TreeSet<>();
        persons.add(p1);
        persons.add(p2);
        persons.add(p3);
        persons.add(p4);

        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="+"]";
     }
 }

自定義類型實現comparable接口

package com.lichennan.collection.map;

import java.util.TreeSet;

public class TreeSetTest04 {
    public static void main(String[] args) {
        Customer c1 = new Customer(23);
        Customer c2 = new Customer(83);
        Customer c3 = new Customer(43);
        Customer c4 = new Customer(23);

        TreeSet<Customer> customers = new TreeSet<>();
        customers.add(c1);
        customers.add(c2);
        customers.add(c3);
        customers.add(c4);

        for ( Customer p : customers){
            System.out.println(p);
        }
    }
}

class Customer implements Comparable<Customer>{
    int age;
    public Customer(int age){
        this.age=age;
    }
    //編寫比較邏輯或比較規則
    @Override
    public int compareTo(Customer c) {

        return this.age-c.age;
    }

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

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章