利用 Comparable 接口创建自己的类的排序顺序,只是实现 compareTo() 方法的问题。通常就是依赖几个数据成员的自然排序。同时类也应该覆盖 equals() 和 hashCode() 以确保两个相等的对象返回同一个哈希码。
这个接口的作用:如果数组或者集合中的(类)元素实现了该接口的话 , 我们就可以调用 Collections.sort 和 Arrays.sort 排序,或应用于有序集合 TreeSet 和 TreeMap 中。
下面设计一个有序的类 Person ,它实现 Comparable 接口,以年龄为第一关键字,姓名为第二关键字升序排序。
Person.java
|
package com.zj.sort.comparable;
public class Person implements Comparable<Person> { private int age ; private String name ;
public Person( int age, String name) { this . age = age; this . name = name; }
public int compareTo(Person person) { int cop = age - person.getAge(); if (cop != 0) return cop; else return name .compareTo(person. name ); }
public int getAge() { return age ; }
public String getName() { return name ; }
public int hashCode() { int result = 17; result = 37 * result + age ; result = 37 * result + name .hashCode(); return result; }
public boolean equals(Object o) { if (!(o instanceof Person)) return false ; Person person = (Person) o; return ( age == person. age ) && ( name .equals(person. name )); }
public String toString() { return ( age + "{" + name + "}" ); } } |
2.1 测试 Arrays.sort ()方法
ArraysSortUnit.java
package com.zj.sort.comparable;
import java.util.Arrays;
import com.zj.compare.Person;
public class ArraysSortUnit {
public static void main(String[] args) {
Person[] ps = { new Person(20, "Tom" ), new Person(20, "Jeff" ),
new Person(30, "Mary" ), new Person(20, "Ada" ),
new Person(40, "Walton" ), new Person(61, "Peter" ),
new Person(20, "Bush" ) };
System. out .println(Arrays.toString (ps));
Arrays.sort (ps);
System. out .println(Arrays.toString (ps));
}
}
本文介绍如何使用Comparable接口为自定义类实现排序逻辑。通过实现compareTo方法,并覆盖equals和hashCode方法,确保了对象间的正确比较及哈希一致性。示例代码展示了如何基于年龄和姓名属性对Person对象进行排序。
1184

被折叠的 条评论
为什么被折叠?



