Java 往TreeSet集合中儲存自定義物件學生,按照學生的年齡進行排序。
阿新 • • 發佈:2018-12-25
Set:無序,不可以重複元素。
|--HashSet:資料結構是雜湊表。執行緒是非同步的。
保證元素唯一性的原理:判斷元素的hashCode值是否相同。
如果相同,還會繼續判斷元素的equals方法,是否為true。
|--TreeSet:可以對Set集合中的元素進行排序。
底層資料結構是二叉樹。
保證元素唯一性的依據:
compareTo方法return 0.
TreeSet排序的第一種方式:讓元素自身具備比較性。
元素需要實現Comparable介面,覆蓋compareTo方法。
也種方式也成為元素的自然順序,或者叫做預設順序。
TreeSet的第二種排序方式。
當元素自身不具備比較性時,或者具備的比較性不是所需要的。
這時就需要讓集合自身具備比較性。
在集合初始化時,就有了比較方式。
需求:
往TreeSet集合中儲存自定義物件學生。
想按照學生的年齡進行排序。
————摘自《畢向東25天》
|--HashSet:資料結構是雜湊表。執行緒是非同步的。
保證元素唯一性的原理:判斷元素的hashCode值是否相同。
如果相同,還會繼續判斷元素的equals方法,是否為true。
|--TreeSet:可以對Set集合中的元素進行排序。
底層資料結構是二叉樹。
保證元素唯一性的依據:
compareTo方法return 0.
TreeSet排序的第一種方式:讓元素自身具備比較性。
元素需要實現Comparable介面,覆蓋compareTo方法。
也種方式也成為元素的自然順序,或者叫做預設順序。
TreeSet的第二種排序方式。
當元素自身不具備比較性時,或者具備的比較性不是所需要的。
這時就需要讓集合自身具備比較性。
在集合初始化時,就有了比較方式。
需求:
往TreeSet集合中儲存自定義物件學生。
想按照學生的年齡進行排序。
記住,排序時,當主要條件相同時,一定判斷一下次要條件。
import java.util.*; class TreeSetDemo { public static void main(String[] args) { TreeSet ts = new TreeSet(); ts.add(new Student("lisi02",22)); ts.add(new Student("lisi007",20)); ts.add(new Student("lisi09",19)); ts.add(new Student("lisi08",19)); //ts.add(new Student("lisi007",20)); //ts.add(new Student("lisi01",40)); Iterator it = ts.iterator(); while(it.hasNext()) { Student stu = (Student)it.next(); System.out.println(stu.getName()+"..."+stu.getAge()); } } } class Student implements Comparable//該介面強制讓學生具備比較性。 { private String name; private int age; Student(String name,int age) { this.name = name; this.age = age; } public int compareTo(Object obj) { //return 0; if(!(obj instanceof Student)) throw new RuntimeException("不是學生物件"); Student s = (Student)obj; System.out.println(this.name+"....compareto....."+s.name); if(this.age>s.age) return 1; if(this.age==s.age) { return this.name.compareTo(s.name); } return -1; /**/ } public String getName() { return name; } public int getAge() { return age; } }
————摘自《畢向東25天》