Comparator、comparable
对更改关闭,对扩展开放,程序更有弹性,可扩展性强。
Extensibility、Scalability
对任意数据类型的数组进行排序,且可以灵活的定义排序策略。
如:定义一个猫对象有高和重量两个属性,可以灵活根据猫对象的属性策略进行排序。
/**
* @description: 比较器接口
* @author: flygo
* @time: 2022/7/4 16:26
*/
public interface Comparator<T> {
int compare(T o1, T o2);
}
/**
* @description: 排序对象
* @author: flygo
* @time: 2022/7/4 11:16
*/
public class Sorter<T> {
public void sort(T[] arr, Comparator<T> comparator) {
for (int i = 0; i < arr.length - 1; i++) {
int minPos = i;
for (int j = i + 1; j < arr.length; j++) {
minPos = comparator.compare(arr[j], (arr[minPos])) == -1 ? j : minPos;
}
swap(arr, i, minPos);
}
}
void swap(T[] arr, int i, int j) {
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
实现比较器
Comparator
接口中的compare
方法,按猫的高度进行比较
/**
* @description: 猫按高比较
* @author: flygo
* @time: 2022/7/4 16:29
*/
public class CatHeightComparator implements Comparator<Cat> {
@Override
public int compare(Cat o1, Cat o2) {
if (o1.getHeight() < o2.getHeight()) return -1;
else if (o1.getHeight() > o2.getHeight()) return 1;
else return 0;
}
}
/**
* @description: 猫按体重比较
* @author: flygo
* @time: 2022/7/4 16:29
*/
public class CatWeightComparator implements Comparator<Cat> {
@Override
public int compare(Cat o1, Cat o2) {
if (o1.getWeight() > o2.getWeight()) return -1;
else if (o1.getWeight() < o2.getWeight()) return 1;
else return 0;
}
}
最终实现效果:可以自定猫的排序策略,对猫数组进行排序。
如排序策略:
CatHeightComparator
、CatWeightComparator
可以灵活根据策略进行排序。
import java.util.Arrays;
/**
* @description: 主方法
* @author: flygo
* @time: 2022/7/4 11:15
*/
public class StrategyMain {
public static void main(String[] args) {
Cat[] arr = {new Cat(3, 3), new Cat(5, 5), new Cat(1, 1)};
Sorter sorter = new Sorter();
// CatHeightComparator comparator = new CatHeightComparator();
CatWeightComparator comparator = new CatWeightComparator();
sorter.sort(arr, comparator);
System.out.println(Arrays.toString(arr));
}
}
Comparator接口只有一个方法,可以定义为函数式接口。如果默认只有一个方法,
@FunctionalInterface
可以省略不写。
@FunctionalInterface
/**
* @description: 比较器接口
* @author: flygo
* @time: 2022/7/4 16:26
*/
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
}
import java.util.Arrays;
/**
* @description: 主方法
* @author: flygo
* @time: 2022/7/4 11:15
*/
public class StrategyMain {
public static void main(String[] args) {
method2();
}
private static void method2() {
Cat[] arr = {new Cat(3, 3), new Cat(5, 5), new Cat(1, 1)};
Sorter<Cat> sorter = new Sorter();
// CatHeightComparator comparator = new CatHeightComparator();
CatWeightComparator comparator = new CatWeightComparator();
sorter.sort(
arr,
(o1, o2) -> {
if (o1.getHeight() < o2.getHeight()) return -1;
else if (o1.getHeight() > o2.getHeight()) return 1;
else return 0;
});
System.out.println(Arrays.toString(arr));
}
}