集合-TreeSet-Comparable,treeset集合

來源:互聯網
上載者:User

集合-TreeSet-Comparable,treeset集合

Student類:name、age屬性 
1 package com.bjpowernode.test01_set2_Comparable; 2 /* 3 * T: type 4 */ 5 public class Student implements Comparable<Student> { 6 private String name; 7 private int age; 8 public String getName() { 9 return name;10 }11 public void setName(String name) {12 this.name = name;13 }14 public int getAge() {15 return age;16 }17 public void setAge(int age) {18 this.age = age;19 }20 public Student(String name, int age) {21 super();22 this.name = name;23 this.age = age;24 }25 public Student() {26 super();27 // TODO Auto-generated constructor stub28 }29 /*@Override30 public int hashCode() {31 final int prime = 31;32 int result = 1;33 result = prime * result + age;34 result = prime * result + ((name == null) ? 0 : name.hashCode());35 return result;36 }37 @Override38 public boolean equals(Object obj) {39 if (this == obj)40 return true;41 if (obj == null)42 return false;43 if (getClass() != obj.getClass())//判斷兩個“對象”的類型是否相同。44 return false;45 Student other = (Student) obj; //向下轉型 46 if (age != other.age)47 return false;48 if (name == null) { //避免出現NullPointerException異常49 if (other.name != null)50 return false;51 } else if (!name.equals(other.name))52 return false;53 return true;54 }*/55 /*56 * 當前對象與參數對象相同時返回 : 057 * 當前對象 大於參數對象 時: 1 正數58 * 當前對象 小於參數對象 時: -1 負數59 */60 @Override61 public int compareTo(Student s) {62 //按年齡排序,如果年齡相同,按姓名排序63 if(this.age == s.age){64 //按姓名排序, 調用字串的compareTo65 return this.name.compareTo(s.name);66 }67 return this.age -s.age;68 }69 70 }
 TreeSet儲存,遍曆,排序輸出
1 package com.bjpowernode.test01_set2_Comparable; 2 3 import java.util.TreeSet; 4 /* 5 * TreeSet中存放元素,預設按自然排序的方式去除重複項,並進行排序的 6 * String和8種封裝類中都指定自然排序方法:實現java.lang.Comparable介面,重寫compareTo方法 7 * 自訂的類放入TreeSet時,也實現實現java.lang.Comparable介面,重寫compareTo方法 8 */ 9 public class StudentTreeSetTest {10 public static void main(String[] args) {11 TreeSet<Student> tree = new TreeSet<>();12 Student s = new Student("Mike", 18);13 Student s1 = new Student("Join", 28);14 Student s3 = new Student("Join", 18);15 Student s4 = new Student("Smith", 18);16 tree.add(s);17 tree.add(s1);18 tree.add(s3);19 tree.add(s4);20 System.out.println(tree.size());21 System.out.println("姓名\t年齡");22 for (Student stu : tree) {23 System.out.println(stu.getName()+"\t"+stu.getAge());24 }25 }26 }

 

聯繫我們

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