package mySort;
import java.util.Arrays;
public class CompareTest {
public static void main(String[] args) {
test1();
test2();
}
/**
ComparabLe接口的使用举例: 自然排序
1.像String、包装类等实现了Comparable接口,重写了compareTo()方法,给出了两个对象大小的比较方式
2.像String、包装类重写compareTo()方法以后,进行了从小到大的排列
3.重写compareTo(obj)的规则:
如果当前对象this大于形参对象obj,则返回正整数,
如果当前对象this小于形参对象obj,则返回负整数,
如果当前对象this等于形参对象obj,则返回零。
4.对于自定义类来说,如果需要排序,我们可以让自定义类实现Comparable接口,重写了compareTo()方法。
需要在compareTo(obj)方法中指明如何排序
*/
public static void test1(){
String[] arr = new String[]{"AA","VV","MM","GG","BB"};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
public static void test2(){
Goods[] arr = new Goods[4];
arr[0] = new Goods("WTY1",124);
arr[1] = new Goods("WTY2",24);
arr[2] = new Goods("WTY3",326);
arr[3] = new Goods("WTY4",128);
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
}
class Goods implements Comparable{//商品类
private String name;
private double price;
public Goods() {
}
public Goods(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Goods{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
//指明商品比较大小的方式:
//价格从低到高排序,再按照产品名称从高到低排序
@Override
public int compareTo(Object o) {
if(o instanceof Goods){
Goods goods = (Goods) o;
//方式一:
if(this.price > goods.price){
return 1;
}else if(this.price < goods.price){
return -1;
}else {
return -this.name.compareTo(goods.name);//前面加了一个负号
}
//方式二:
//return Double.compare(this.price,goods.price);
}
throw new RuntimeException("传入的数据类型不一致! ");
}
}
package mySort;
import java.util.ArrayList;
import java.util.Collections;
public class DIYsort {
public static void main(String[] args) {
ArrayList<Shape> list = new ArrayList<>();
Circle circle1 = new Circle(2.0);
Circle circle2 = new Circle(3.0);
Triangle triangle1 = new Triangle(1, 2);
Triangle triangle2 = new Triangle(2, 2);
list.add(circle1);
list.add(circle2);
list.add(triangle1);
list.add(triangle2);
Collections.sort(list);
list.forEach(e -> {
System.out.println(e.getArea());
});
}
}
interface Shape extends Comparable<Shape>{
double getArea();
@Override
int compareTo(Shape o);
}
class Circle implements Shape{
private double r;
public Circle() {
}
public Circle(double r) {
this.r = r;
}
@Override
public double getArea() {
return Math.PI * r * r;
}
@Override
public int compareTo(Shape o) {
Double a1 = getArea();
Double a2 = o.getArea();
return a1.compareTo(a2);
}
}
class Triangle implements Shape{
private double length;
private double width;
public Triangle() {
}
public Triangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double getArea() {
return length * width;
}
@Override
public int compareTo(Shape o) {
Double a1 = getArea();
Double a2 = o.getArea();
return a1.compareTo(a2);
}
}