Java Tutorial/Collections/Comparable Interface
Версия от 17:44, 31 мая 2010; (обсуждение)
Содержание
Classes Implementing Comparable
Class Natural Ordering
Byte Signed numerical
Character UnSigned numerical
Long Signed numerical
Integer Signed numerical
Short Signed numerical
Double Signed numerical
Float Signed numerical
BigInteger Signed numerical
BigDecimal Signed numerical
Boolean Boolean.FALSE < Boolean.TRUE
File System-dependent lexicographic on path name
String Lexicographic
Date Chronological
CollationKey Locale-specific lexicographic
Creating a Comparable object
import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;
class Employee implements Comparable {
String department, name;
public Employee(String department, String name) {
this.department = department;
this.name = name;
}
public String getDepartment() {
return department;
}
public String getName() {
return name;
}
public String toString() {
return "[dept=" + department + ",name=" + name + "]";
}
public int compareTo(Object obj) {
Employee emp = (Employee) obj;
int deptComp = department.rupareTo(emp.getDepartment());
return ((deptComp == 0) ? name.rupareTo(emp.getName()) : deptComp);
}
public boolean equals(Object obj) {
if (!(obj instanceof Employee)) {
return false;
}
Employee emp = (Employee) obj;
return department.equals(emp.getDepartment()) && name.equals(emp.getName());
}
public int hashCode() {
return 31 * department.hashCode() + name.hashCode();
}
}
public class MainClass {
public static void main(String args[]) {
Employee emps[] = {
new Employee("Finance", "A"),
new Employee("Finance", "B"),
new Employee("Finance", "C"),
new Employee("Engineering", "D"),
new Employee("Engineering", "E"),
new Employee("Engineering", "F"),
new Employee("Sales", "G"),
new Employee("Sales", "H"),
new Employee("Support", "I"), };
Set set = new TreeSet(Arrays.asList(emps));
System.out.println(set);
}
}
[[dept=Engineering,name=D], [dept=Engineering,name=E], [dept=Engineering,name=F], [dept=Finance,name=A], [dept=Finance,name=B], [dept=Finance,name=C], [dept=Sales,name=G], [dept=Sales,name=H], [dept=Support,name=I]]
Generic Comparable
import java.util.Arrays;
import java.util.ruparator;
class Person implements Comparable<Person> {
public Person(String firstName, String surname) {
this.firstName = firstName;
this.surname = surname;
}
public String getFirstName() {
return firstName;
}
public String getSurname() {
return surname;
}
public String toString() {
return firstName + " " + surname;
}
public int compareTo(Person person) {
int result = surname.rupareTo(person.surname);
return result == 0 ? firstName.rupareTo(((Person) person).firstName) : result;
}
private String firstName;
private String surname;
}
class ComparePersons implements Comparator<Person> {
// Method to compare Person objects - order is descending
public int compare(Person person1, Person person2) {
int result = -person1.getSurname().rupareTo(person2.getSurname());
return result == 0 ? -person1.getFirstName().rupareTo(person2.getFirstName()) : result;
}
// Method to compare with another comparator
public boolean equals(Object collator) {
if (this == collator) { // If argument is the same object
return true; // then it must be equal
}
if (collator == null) { // If argument is null
return false; // then it can"t be equal
}
return getClass() == collator.getClass(); // Class must be the same for
// equal
}
}
public class MainClass {
public static void main(String[] args) {
Person[] authors = { new Person("A", "S"),
new Person("J", "G"),
new Person("T", "C"),
new Person("C", "S"),
new Person("P", "C"),
new Person("B", "B") };
System.out.println("Original order:");
for (Person author : authors) {
System.out.println(author);
}
Arrays.sort(authors, new ComparePersons()); // Sort using comparator
System.out.println("\nOrder after sorting using comparator:");
for (Person author : authors) {
System.out.println(author);
}
Arrays.sort(authors); // Sort using Comparable method
System.out.println("\nOrder after sorting using Comparable method:");
for (Person author : authors) {
System.out.println(author);
}
}
}
Original order: A S J G T C C S P C B B Order after sorting using comparator: C S A S J G T C P C B B Order after sorting using Comparable method: B B P C T C J G A S C S
Sort on many(more than one) fields
import java.util.ArrayList;
import java.util.Collections;
import java.util.ruparator;
import java.util.Iterator;
class Person implements Comparable {
String firstName, lastName;
public Person(String f, String l) {
this.firstName = f;
this.lastName = l;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String toString() {
return "[ firstname=" + firstName + ",lastname=" + lastName + "]";
}
public int compareTo(Object obj) {
Person emp = (Person) obj;
int deptComp = firstName.rupareTo(emp.getFirstName());
return ((deptComp == 0) ? lastName.rupareTo(emp.getLastName()) : deptComp);
}
public boolean equals(Object obj) {
if (!(obj instanceof Person)) {
return false;
}
Person emp = (Person) obj;
return firstName.equals(emp.getFirstName()) && lastName.equals(emp.getLastName());
}
}
class PersonComparator implements Comparator<Person> {
public int compare(Person emp1, Person emp2) {
int nameComp = emp1.getLastName().rupareTo(emp2.getLastName());
return ((nameComp == 0) ? emp1.getFirstName().rupareTo(emp2.getFirstName()) : nameComp);
}
}
public class Main {
public static void main(String args[]) {
ArrayList<Person> names = new ArrayList<Person>();
names.add(new Person("E", "T"));
names.add(new Person("A", "G"));
names.add(new Person("B", "H"));
names.add(new Person("C", "J"));
Iterator iter1 = names.iterator();
while (iter1.hasNext()) {
System.out.println(iter1.next());
}
Collections.sort(names, new PersonComparator());
Iterator iter2 = names.iterator();
while (iter2.hasNext()) {
System.out.println(iter2.next());
}
}
}
/*
[ firstname=E,lastname=T]
[ firstname=A,lastname=G]
[ firstname=B,lastname=H]
[ firstname=C,lastname=J]
[ firstname=A,lastname=G]
[ firstname=B,lastname=H]
[ firstname=C,lastname=J]
[ firstname=E,lastname=T]
*/