JAVA學習筆記整理六(類集框架)
阿新 • • 發佈:2018-12-30
public class SetTest { public static void main(String[] args) { // hashSet Set hashSet = new HashSet(); hashSet.add("A"); hashSet.add("A"); hashSet.add("B"); hashSet.add("C"); hashSet.add("C"); hashSet.add("D"); System.out.println("hashSet:" + hashSet); // hashSet:[D, A, B, C] // treeSet Set treeSet = new TreeSet(); treeSet.add("D"); treeSet.add("A"); treeSet.add("C"); treeSet.add("D"); treeSet.add("B"); treeSet.add("A"); System.out.println("treeSet:" + treeSet); // treeSet:[A, B, C, D] // myTreeSet Set myTreeSet = new TreeSet(); myTreeSet.add(new Child("張三", 18)); myTreeSet.add(new Child("李四", 20)); myTreeSet.add(new Child("王五", 21)); myTreeSet.add(new Child("王五", 21)); myTreeSet.add(new Child("張三", 19)); myTreeSet.add(new Child("張三", 18)); System.out.println("myTreeSet:" + myTreeSet); // myTreeSet:[姓名:張三==年齡:18, 姓名:張三==年齡:19, //姓名:李四==年齡:20, 姓名:王五==年齡:21] // SortedSet SortedSet sortedSet = new TreeSet(); sortedSet.add("A"); sortedSet.add("B");//同樣不能放入重複 sortedSet.add("B"); sortedSet.add("C"); sortedSet.add("A"); sortedSet.add("D"); sortedSet.add("E"); System.out.println("第一個元素:" + sortedSet.first());//第一個元素:A System.out.println("最後一個元素:" + sortedSet.last());//最後一個元素:E System.out.println("headSet元素:" + sortedSet.headSet("C")); //C的前面,不包括C headSet元素:[A, B] System.out.println("tailSet元素:" + sortedSet.tailSet("C")); //C的後面,包括 CtailSet元素:[C, D, E] System.out.println("subSet元素:" + sortedSet.subSet("B", "D")); //B、D中間,包含B不包含D subSet元素:[B, C] } } class Child implements Comparable { // TreeSet中為有序排列,所以對於自定義的類使用TreeSet進行存放時, //對於一個物件必須指定好排序規則,需要實現Commparable接口才能正常使用 private String name; private int age; public Child(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "姓名:" + this.name + "==年齡:" + this.age; } @Override public boolean equals(Object obj) {// 比較方法過載,用於進行比較兩個物件,並去除重複物件 if (this == obj) {// 地址相等 return true;// 是同一個物件 } if (this == null) {// 地址為空 if (obj != null) return false;// 不是同一個物件 } Child temp = (Child) obj;// 進行向下轉型 if ((this.name.equals(temp.name)) && (this.age != temp.age)) {// 依次判斷屬性是否相等 return true;// 全部相等,是一個物件 } else { return false; } } @Override public int hashCode() {// 對於重複的判斷,只覆寫equals方法不夠,還需要覆寫hashCode方法, //利用指定的公式將類中全部屬性進行計算,以求出一個不會重複的雜湊碼,從而判斷不重複 return this.name.hashCode() * this.age;// 指定雜湊碼編寫公式 } @Override public int compareTo(Child o) { if (this == o) {// 地址相等 return 0;// 相等返回0,大於返回正數,小於返回負數 } if (this == null) {// 地址為空 if (o != null) return -1; } if (!this.name.equals(o.name)) {// 姓名不相等則按姓名排 return this.name.compareTo(o.name);// 按字典順序比較兩個字串 } // return o.age - this.age;// 年齡按從o到this的順序排 return this.age - o.age;// 年齡按從this到o的順序排 } }