public
interface Comparable{
public
int compareTo(Object o);
}
要本身實現該接口,從
API看到該接口只有一個方法,
compareTo
的約定是:
將當前這個對象與指定的對象進行順序比較,當該對象小於、等於或大於指定對象時,分別返回一個負整數、0或正整數,若是沒法進行比較,則拋出ClassCastException異常。(泛型沒有掌握,因此compareTo的參數用Object ,因此比較以前必須進行強制轉換。若是學會了泛型就方便多了)。
如今咱們寫個例子來實踐一下,重寫comparable接口的compareTo的方法,按照咱們所定義的「規則」排序。
Student類實現了Comparable接口並重寫了compareTo的方法,代碼以下:
Java代碼
public
class Student
implements Comparable {
private
int age;
private String name;
public
int getAge() {
return age;
}
public
void setAge(
int age) {
this.age = age;
}
public String getName() {
return name;
}
public
void setName(String name) {
this.name = name;
}
public Student() {
}
public Student(String name,
int age) {
this.name = name;
this.age = age;
}
public
boolean equals(Object obj) {
boolean rusult =
false;
if (
this == obj) {
rusult =
true;
}
if (!(obj
instanceof Student)) {
rusult =
false;
}
Student stu = (Student) obj;
if ((stu.getName().equals(
this.name)) && (stu.getAge() ==
this.age)) {
rusult =
true;
}
else {
rusult =
false;
}
return rusult;
}
public
int hashCode() {
return (
this.name.hashCode() +
this.age) * 31;
}
public String toString() {
return
"name=" +
this.name +
" age=" +
this.age;
}
public
int compareTo(Object o) {
Student stu = (Student) o;
if (
this.getName().compareTo(stu.getName()) > 0) {
return 1;
}
if (
this.getName().compareTo(stu.getName()) < 0) {
return -1;
}
if (
this.age > stu.getAge() ) {
return 1;
}
if (
this.age < stu.getAge()) {
return -1;
}
return 0;
}
}
從重寫的compareTo方法能夠看出,排序「規則」是這樣的:首先按照學生姓名排序,若是學生姓名相同的話,再按照學生年齡排序。
寫一個測試類,測試一下,代碼以下:
import java.util.*;
public
class TreeSetTest {
public
static
void main(String args[]) {
Set set =
new TreeSet();
Student stu1 =
new Student(
"EEE", 12);
Student stu2 =
new Student(
"FFF", 11);
Student stu3 =
new Student(
"DDD", 13);
set.add(stu1);
set.add(stu2);
set.add(stu3);
Iterator it = set.iterator();
while (it.hasNext()) {
Object obj = it.next();
System.out.println(obj);
}
}
}
運行結果爲:
name=DDD age=13
name=EEE age=12
name=FFF age=11
當學生姓名相同時,再按照學生的年齡排序,若是把測試類的三個例子改成:
Student stu1 = new Student("EEE", 12);
Student stu2 = new Student("EEE", 11);
Student stu3 = new Student("DDD", 13);
則運行結果爲:
name=DDD age=13
name=EEE age=11
name=EEE age=12