Java中Comparable与Comparator的区别

xiaoxiao2025-08-12  25

 

/* *java中Comparable & Comparator都是用来实现集合中元素的比较,用来进行排序 *区别:Comparable是集合中内部定义的方法实现的排序, * Comparator是外部定义的排序方法, *想要实现排序,就要在集合外定义Comparator接口的方法或在集合内实现Comparable接口的方法 *Comparator位于java.util下 *Comparable位于java.lang下 * */ //方法一: @SuppressWarnings("all") public class TestCompareTo { public static void main(String[] args) { Circle[] cir = new Circle[4]; for (int i = 0; i < cir.length; ++i) { cir[i] = new Circle(Math.random() * 9 + 1); } Arrays.sort(cir,new Comparator() { @Override public int compare(Object o1, Object o2) { Circle c1 = (Circle) o1; Circle c2 = (Circle) o2; if(c1.getRadius()> c2.getRadius()){ return 1; }else if(c1.getRadius()< c2.getRadius()){ return -1; } return 0; }}); for (Circle circle : cir) { System.out.println(circle); } } } class Circle { private double radius; public Circle() { super(); } public Circle(double radius) { super(); this.radius = radius; } public double getRadius() { return radius; } public void setRadius(double radius) { this.radius = radius; } @Override public String toString() { return "Circle [radius=" + radius + "]"; } } //方法二: @SuppressWarnings("all") public class TestCompareTo2{ public static void main(String[] args) { Rectangle[] rec = new Rectangle[3]; for(int i=0; i<rec.length; ++i){ rec[i] = new Rectangle(10-i, 8-i); } Arrays.sort(rec); for (Rectangle rectangle : rec) { System.out.println(rectangle); } } } class Rectangle implements Comparable{ private int height; private int width; public Rectangle(int height, int width) { super(); this.height = height; this.width = width; } private int getArea(){ return height* width; } @Override public String toString() { return "Rectangle [height=" + height + ", width=" + width + "]"; } @Override public int compareTo(Object o) { Rectangle other = (Rectangle) o; if(this.getArea()> other.getArea()){ return 1; }else if(this.getArea() < other.getArea()){ return -1; } return 0; } }

 

转载请注明原文地址: https://www.6miu.com/read-5034742.html

最新回复(0)