# 對象<SUP>(物件)</SUP>的排序
###### tags: `java`
[TOC]
---
| | `Comparable` | `Comparator` |
| ------------ | ---------------------------- | ---------------------- |
| 進行排序比較 | 某特定條件為默認自然排序條件 | 可分別針對多個不同條件 |
| 實作方式 | 於欲被排序的 class | 於獨立的 class |
| `@Override` | `compareTo()` | `compare()` |
## Implementing [`Comparable<T>`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Comparable.html) Interface
the value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.
**實作**並 **`@Override`**:
```java
public class Example implements Comparable<Example> {
private Date createdAt;
private Date changedAt;
@Override
public int compareTo(ComparableImpl other) {
return createdAt.compareTo(
other.createdAt
);
}
}
```
進行排序:
```java
List<Example> examples = new ArrayList<>();
// populating omitted for brevity
Collections.sort(examples);
```
## Implementing [`Comparator<T>`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Comparator.html) Interface
**實作**並 **`@Override`**:
```java
public class ExampleCreatedComparator implements Comparator<Example> {
// other boilerplate codes omitted for brevity
@Override
public int compare(Example first, Example second) {
return Long.compare(
first.getCreatedAt().getTime(),
second.getCreatedAt().getTime()
);
}
}
```
```java
public class ExampleChangedComparator implements Comparable<Example> {
// other boilerplate codes omitted for brevity
@Override
public int compare(Example first, Example second) {
return Long.compare(
first.getChangedAt().getTime(),
second.getChangedAt().getTime()
);
}
}
```
進行排序:
```java
Collections.sort(
examples,
new ExampleCreatedComparator()
);
```
```java
Collections.sort(
examples,
new ExampleChangedComparator()
);
```