Java中比较器的使用Compare和Comparator
Comparable和Comparator接口都是为了对类进行比较,众所周知,诸如Integer,double等基本数据类型,java可以对他们进行比较,而对于类的比较,需要人工定义比较用到的字段比较逻辑。可以把Comparable理解为内部比较器,而Comparator是外部比较器,基本的写法如下: class Apple implements Comparable<Apple>{ int id; double price; public Apple(int id, double price) { this.id = id; this.price = price; } public int compareTo(Apple o) { //return Double.compare(this.getPrice(),o.getPrice()); if (Math.abs(this.price-o.price)<0.001) return 0; else return (o.price-this.price)>0?1:-1; } @Override public String toString() { return "Apple{" + "id=" + id + ", price=" + price + '}'; } }``` class AESComparator implements