標籤: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