Java 中 Comparable 和 Comparator 的区别
javaobject oriented programmingprogramming更新于 2025/7/24 6:36:17
Comparable 和 comparator 都是可用于对集合元素进行排序的接口。Comparator 接口属于 java.util 包,而 Comparable 属于 java.lang 包。Comparator 接口使用提供给它的两个对象对集合进行排序,而 Comparable 接口比较"this"是指提供给它的一个对象。
| Sr.不。 | Key | Comparable | Comparator |
|---|---|---|---|
| 1 | 方法 | Comparable 接口有一个方法 compareTo(Object a ) | Comparator 有一个方法 compare(Object o1, Object O2) |
| 2 | 排序用途 | Collection.sort(List)方法可用于对Comparable类型对象集合进行排序。 | Collection.sort(List, Comparator)方法可用于对Comparator类型对象集合进行排序。 |
| 3 | 排序序列 | Comparable 提供单一排序序列。 | Comparator 提供多重排序序列。 |
| 4 | 包 | Comparable 接口属于 java.lang 包。 | Comparator 接口属于 java.util 包。 |
Comparable 示例
public class ComparableExample {
public static void main(String[] args) {
List<Laptop> laptopList = new ArrayList<>();
laptopList.add(new Laptop("HCL", 16, 800));
laptopList.add(new Laptop("Apple", 8, 100));
laptopList.add(new Laptop("Dell", 4, 600));
Collections.sort(laptopList);
for (Laptop lap : laptopList) {
System.out.println(lap.getRam());
}
}
}
public class Laptop implements Comparable<Laptop> {
String name;
int ram;
int price;
public Laptop(String name, int ram, int price) {
super();
this.name = name;
this.ram = ram;
this.price = price;
}
public String getName() {
return name;
}
public int getRam() {
return ram;
}
public void setRam(int ram) {
this.ram = ram;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public int compareTo(Laptop o) {
if (this.ram > o.getRam())
return 1;
else {
return -1;
}
}
}
输出
4 8 16
Comparator 示例
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Laptop implements Comparator {
String name;
int ram;
int price;
public Laptop(String name, int ram, int price) {
super();
this.name = name;
this.ram = ram;
this.price = price;
}
public String getName() {
return name;
}
public int getRam() {
return ram;
}
public void setRam(int ram) {
this.ram = ram;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public int compare(Laptop o1, Laptop o2) {
if (o1.getRam() < o2.getRam()) {
return -1;
}else if (o1.getRam() > o2.getRam()) {
return 1;
} else {
return 0;
}
}
public static void main(String[] args) {
List laptopList = new ArrayList<>();
laptopList.add(new Laptop("HCL", 16, 800));
laptopList.add(new Laptop("Apple", 8, 100));
laptopList.add(new Laptop("Dell", 4, 600));
Comparator com = (Laptop o1, Laptop o2) -> o1.getName().compareTo(o2.getName());
Collections.sort(laptopList, com);
for (Laptop lap : laptopList) {
System.out.println(lap.getName());
}
}
}
输出
Apple Dell HCL
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

