Person(30, "Mary"), "Mary");
map.put(new Person(20, "Ada"), "Ada");
map.put(new Person(40, "Walton"), "Walton");
map.put(new Person(61, "Peter"), "Peter");
map.put(new Person(20, "Bush"), "Bush");
System.out.println(map);
}
}
结果:
{20{Ada}=Ada, 20{Bush}=Bush, 20{Jeff}=Jeff, 20{Tom}=Tom, 30{Mary}=Mary, 40{Walton}=Walton, 61{Peter}=Peter}
3. Comparator接口
public interface Comparator<T> {
int compare(T o1, T o2);
boolean equals(Object obj);
}
若一个类不能用于实现java.lang.Comparable,或者不喜欢缺省的Comparable行为并想提供自己的排序顺序(可能多种排序方式),你可以实现Comparator接口,从而定义一个比较器。
1)int compare(Object o1, Object o2): 对两个对象o1和o2进行比较,如果o1位于o2的前面,则返回负值,如果在排序顺序中认为o1和o2是相同的,返回0,如果o1位于o2的后面,则返回正值。
2)与Comparable相似,0返回值不表示元素相等。一个0返回值只是表示两个对象排在同一位置。由Comparator用户决定如何处理。
3)boolean equals(Object obj): 指示对象obj是否和比较器相等。该方法覆写Object的equals()方法,检查的是Comparator实现的等同性,不是处于比较状态下的对象。
下面设计一个定义完整equals方法和hashCode方法的类Person。
Person.java
package com.zj.sort.comparator;
public class Person {
private String firstName;
private String lastName;
private int age;
public Person(int age, String firstName, String lastName) {
this.age = age;
this.firstName = firstName;
this.lastName = lastName;
}
public int getAge() {
return age;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int hashCode() {
int result = 17;
result = 37 * result + age;
result = 37 * result + firstName.hashCode();
result = 37 * result + lastName.hashCode();
return result;
}
public boolean equals(Object o) {
if (!(o instanceof Person))
return false;
Person p = (Person) o;
return (age == p.age) && (firstName.equals(p.firstName))
&& (lastName.equals(p.lastName));
}
public String toString() {
return (age + "{" + firstName + " " + lastName + "}");
}
}
Java:比较与排序(4)
时间:2011-02-25 zhangjunhd
下面设计两个比较器。
FirstNameComparator.java
package com.zj.sort.comparator;
import java.util.Comparator;
//实现按FirstName优先排序
public class FirstNameComparator implements Comparator<Person> {
public int compare(Person person, Person anotherPerson) {
String lastName1 = person.getLastName().toUpperCase();
String firstName1 = person.getFirstName().toUpperCase();
String lastName2 = anotherPerson.getLastName().toUpperCase();
String firstName2 = anotherPerson.getFirstName().toUpperCase();
if (firstName1.equals(firstName2))
|