[javaSE] 集合架構(TreeSet),javasetreeset

來源:互聯網
上載者:User

[javaSE] 集合架構(TreeSet),javasetreeset

TreeSet:可以對Set集合中的元素排序,預設按照ascii表排序,二叉樹結構

左邊叉是小的,右邊叉是大的

 

儲存自訂對象

定義一個類Student實現Comparable類,使自訂類具備比較性

定義屬性年齡age

定義屬性姓名name

實現compareTo()方法,傳遞進來另一個Student對象

判斷當前Student對象的age大於另一個Student對象的age,返回1,否則返回-1

 

擷取Student對對象

調用TreeSet對象的add()方法,參數:Student對象

遍曆集合

import java.util.TreeSet;public class TreeSetDemo {    /**     * @param args     */    public static void main(String[] args) {        TreeSet<Student> treeset=new TreeSet<Student>();        treeset.add(new Student("taoshihan1",30));        treeset.add(new Student("taoshihan2",20));        treeset.add(new Student("taoshihan3",40));        for(Student student:treeset){            System.out.println(student.name+"==="+student.age);        }                            }}class Student implements Comparable<Student>{        public int age;    public String name;    public Student(String name,int age) {        this.name=name;        this.age=age;    }    @Override    public int compareTo(Student o) {        if(o.age<this.age){            return 1;        }else{            return -1;        }    }    }

 

 

結果:

taoshihan2===20

taoshihan1===30

taoshihan3===40

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.