java學習之treeset

來源:互聯網
上載者:User

標籤:ceo   定義   ext   null   getname   str   col   exception   ide   

Set:無序,不可以重複元素

  |--HashSet:資料結構是雜湊表,線程是非同步的。

          保證元素唯一性的原理:判斷元素的hashcode值是否相同

            如果相同,還會繼續判斷元素的equals方法,是否為true

 

  |--TreeSet:可以對Set集合中的元素進行排序

 

注意:排序時,當主要條件相同時,一定要判斷一下次要條件(否則會被認為是同一個對象而不被加入)

 1 import java.util.Iterator; 2 import java.util.TreeSet; 3  4 /** 5  * 需求: 6  * 往treeset集合中儲存自訂對象學生   7  * 想按照學生的年齡進行排序 8  */ 9 public class PackageDemo {10 11     public static void main(String[] args) {12         TreeSet ts=new TreeSet();13         ts.add(new Student("皮卡丘1",20));14         ts.add(new Student("皮卡丘",20));15         ts.add(new Student("皮卡",19));16         ts.add(new Student("雷卡",21));17         ts.add(new Student("雷卡",21));18         19         Iterator it=ts.iterator();20         21         while(it.hasNext()) {22             Student student=(Student)it.next();23             System.out.println(student.getName()+"...."+student.getAge());24         }25         26     }27 28 }29 class Student implements Comparable{//該介面強制讓學生具有比較性30     private String name;31     private int age;32     public Student(String name,int age) {33         this.name=name;34         this.age=age;35     }36     public String getName() {37         return name;38     }39     public int getAge() {40         return age;41     }42     @Override43     public int compareTo(Object o) {44         if(null == o) {45             throw new RuntimeException("傳進一個Null 物件");46         }47         if(!(o instanceof Student)) {48             throw new RuntimeException("傳進來的不是學生類");49         }50         Student student=(Student)o;51         if(this.age>student.age) {52             return 1; 53         }else if(this.age==student.age) {54             return this.name.compareTo(student.name);//注意:排序時,當主要條件相同時,一定要判斷一下次要條件(否則會被認為是同一個對象而不被加入)55         }56         return -1;57     }58     59     60 }

 

java學習之treeset

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.