黑馬程式設計師 筆記(十三)——集合框架
阿新 • • 發佈:2018-12-26
- 應用場合:當元素自身不具備比較性時,或者具備的比較性不是所需要的。
- 比較器的定義:定義一個類實現Comparator介面,覆蓋其中的compare()方法。compare()方法中定義的是比較的內容。
- 當集合中的元素和集合都有比較的功能的時候,輸出的結果是按照集合的比較方式排序的。
- 示例:
import java.util.*; //匯入包 class Student implements Comparable //定義學生類,並且讓其具有比較性 { private int age; private String name; private String id; Student(String name,int age,String id) { this.name = name; this.age = age; this.id = id; } public int compareTo(Object obj) { if (!(obj instanceof Student)) throw new RuntimeException("不是學生物件"); else { System.out.println(this.getName()+" "+this.getAge()); Student s = (Student) obj; if(this.age != s.age) return this.age - s.age; else if(this.name != s.name) return this.name.compareTo(s.name); return this.id.compareTo(s.id); } } public String getName() { return(this.name); } public int getAge() { return(this.age); } public String getId() { return(this.id); } } class MyCompartor implements Comparator //定義一個比較器 { public int compare(Object obj1,Object obj2) { if (!(obj1 instanceof Student)&&(obj2 instanceof Student)) throw new RuntimeException(obj1+"and"+obj2+"中有物件不是學生類"); else { Student stu1 = (Student) obj1; Student stu2 = (Student) obj2; int num1 = new Integer(stu1.getName().length()).compareTo(new Integer(stu2.getName().length())); if (num1 == 0) { int num2 = new Integer(stu1.getAge()).compareTo(new Integer(stu2.getAge())); if(num2 == 0) { return new String(stu1.getId()).compareTo(new String(stu2.getId())); } return num2; } return num1; } } } class MyTreeSet { public static void main(String[] args) { TreeSet ts = new TreeSet(new MyCompartor()); ts.add(new Student("Zhang,Honemi",23,"520")); ts.add(new Student("Zhang,Honemi",22,"520")); ts.add(new Student("Zhang,Honemi",25,"520")); ts.add(new Student("Zhang,Honemi",23,"521")); ts.add(new Student("Zhang,Honemix",23,"520")); for (Iterator it = ts.iterator();it.hasNext() ; ) { Student stu = (Student)it.next(); System.out.println(stu.getName()+"……"+stu.getAge()+"……"+stu.getId()); } } }