Compare类
-
Comparable接口 自然排序
1.像String、包装类等实现了Comparable接口,重写了compareTo()方法
2.String、包装类重写了compareTo()方法后,进行了从小到大的排列
@Test
public void test(){
String[] strings = {"aa", "bb", "dd", "cc"};
Arrays.sort(strings);
System.out.println(Arrays.toString(strings));//[aa, bb, cc, dd]
}
-
非包装类的自定义类
需要重写compareTo()方法
/** * Created by KingsLanding on 2022/6/21 17:24 */ public class Book implements Comparable { private String name; private int price; public Book() { } public Book(String name, int price) { this.name = name; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "book{" + "name='" + name + '\'' + ", price=" + price + '}'; } @Override public int compareTo(Object o) { //instanceof关键字:判断左边对象是否是右边类的实例 if(o instanceof Book){ Book book= (Book)o; if (this.price > book.price) { return 1; } else if (this.price < book.price) { return -1; }else { return this.name.compareTo(book.name); } } // return 0; throw new RuntimeException("数据不匹配"); } }
/** * 自然排序 java.lang.Comparable */ @Test public void test1(){ Book[] books = new Book[4]; books[0]=new Book("三体",50); books[1]=new Book("全频段断阻式干扰",40); books[2]=new Book("诗云",30); books[3]=new Book("aaaa",30); Arrays.sort(books); System.out.println(Arrays.toString(books));//[book{name='aaaa', price=30}, book{name='bbbb', price=30}, book{name='cccc', price=40}, book{name='dddd', price=50}] }
-
Comparator 定制排序 :java.util.Comparator
1.背景-
当元素的类型没有实现java.lang.Comparable接口而又不方便修改代码
-
或者实现了,但是该接口的排序规则不适合当前的操作,就可以使用Comparator的对象来排
2.重写compare(Object o1,Object o2)方法,比较o1和o2的大小
- 如果方法返回正整数,则表示o1>o2;
- 如果返回0,表示相等
- 如果返回负整数,表示o1<o2
-
-
Comparable与Comparator使用对比
-
Comparable接口方式一旦确定,就保证Comparable接口实现类的对象在任何位置都可以比较大小
-
Comparator接口属于临时性的比较
-
@Test
public void test2(){
Book[] books = new Book[4];
books[0]=new Book("三体",50);
books[1]=new Book("全频段断阻式干扰",40);
books[2]=new Book("诗云",30);
books[3]=new Book("aaaa",30);
Arrays.sort(books, new Comparator<Book>() {
//指明商品比较大小的方式,按照产品名称从低到高排序,再按照价格从高到低
@Override
public int compare(Book o1, Book o2) {
if(o1.getName().equals(o2.getName())){
return -Integer.compare(o1.getPrice(),o2.getPrice());
}else {
return o1.getName().compareTo(o2.getName());
}
}
});
System.out.println(Arrays.toString(books));
}