Java中的几种比较器,对象比较,二维数组排序

Java中的几种比较器

一般涉及到对象数组的排序时,我们需要比较数组中的对象进行我们想要的排序。

情况一

对象简单,仅仅只是比较两个引用指向同一个对象,对象的地址是否相同。用“==”即可实现

情况二

如果对象复杂,比如包含不同的属性等

  1. 对于不适用内置排序方法,可通过覆写equals()方法去实现

对于调用内置排序方法。

  1. 让自己编写的类继承Comparable接口,并实现compareTo()方法, 就可以直接调用Arrays.sort()进行想要的排序。

    import java.util.Arrays;
     
    class BookCook implements Comparable<BookCook>{
    	private String title;
    	private double price;
    	public BookCook(String title,double price){
    		this.title = title;
    		this.price = price;
    	}
    	@Override
    	public String toString() {
    		return "书名:"+this.title+",价格:"+this.price;
    	}
    	@Override
    	public int compareTo(BookCook o) {
    		if(this.price > o.price){
    			return 1;
    		}else if(this.price < o.price){
    			return -1;
    		}else{
    			return 0;
    		}
    	}
    }
    
    

如果要在已经开发好的代码的基础上完善对象的比较功能时,又不想更改之前的代码。

  1. 定义一个对象比较器,继承Comparator接口,并实现compare()方法

    class Student {
    	private String name;
    	private double score;
    	public Student(String name,double score){
    		this.name = name;
    		this.score = score;
    	}
    	public double getScore(){
    		return this.score;
    	}
    	@Override
    	public String toString() {
    		return "姓名:"+this.name+",分数:"+this.score;
    	}
    	
    }
    class StudentComparator implements Comparator<Student> {
    	@Override
    	public int compare(Student o1,Student o2) {
    		if(o1.getScore() > o2.getScore()){
    			return 1;
    		}else if(o1.getScore() < o2.getScore()){
    			return -1;
    		}else{
    			return 0;
    		}
    	}
    }
    public class TestComparator {
     
    	public static void main(String[] args) {
    		
    		Student[] sts = new Student[]{
    				new Student("小戴",60),
    				new Student("小王",90),
    				new Student("老王",80),
    				new Student("小萱",95)
    		};
    		
    		java.util.Arrays.sort(sts, new StudentComparator());
    		System.out.println(java.util.Arrays.toString(sts));
    	}
    }
    

简写

假如要比较people数组【身高,年龄】-》【【3,2】【4,4】【4,3】】

Arrays.sort(people, new Comparator<int[]>() {
            public int compare(int[] person1, int[] person2) {
                if (person1[0] != person2[0]) {
                    //按身高降序
                    return person2[0] - person1[0];
                } else {
                    //按年龄升序
                    return person1[1] - person2[1];
                }
            }
        });
#【【43】【44】【32】】
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tacit-lxs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值