1. 程式人生 > >另一種比較器:Comparator

另一種比較器:Comparator

span 問題 com pre log implement nts face spa

package comparatordemo.cn;

import java.util.Comparator;

/*
 * 一個對象的初期,並沒有實現comparable 接口,此時肯定無法進項對象的排序操作,所以為了解決這個問題,
 * Java又定義了另一個比較器的操作接口,但是前提是:必須先定義好一個比較規則類出來
 * 接口的定義如下:
 * public interface Comparator<T>{
 * public int compare(T o1, T o2) ;
 * boolean equals(Object obj) ;
 *}
 */
//定義一個person類
class Person{ private String name; private int age; public Person(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; }
public int getAge() { return age; } public void setAge(int age) { this.age = age; } //復寫equals方法 public boolean equals(Object obj){ if (this==obj) { return true; } if (!(obj instanceof Person)) { return false; } Person p
= (Person)obj; if (this.age==p.age&&this.name.equals(p.name)) { return true; } else { return false; } } //重寫tostring方法 public String toString(){ return this.getName()+this.getAge(); } } //定義一個比較規則 class PersonComparator implements Comparator<Person>{ public int compare(Person p1, Person p2){ if (p1.equals(p2)) { return 0; } else if (p1.getAge()<p2.getAge()) { return 1; } else { return -1; } } } public class ComparatorDemo { public static void main(String[] args) { //創建一個對象數組 Person stu[] = {new Person("張三",22),new Person("張三",20),new Person("李四",22),new Person("王五",30),new Person("趙六",40)}; //排序 java.util.Arrays.sort(stu,new PersonComparator()); //遍歷數組 for (int i = 0; i < stu.length; i++) { System.out.println(stu[i]); } } }

另一種比較器:Comparator