Comparabel实现类之间的比较

概论

在平时编码时免不了要进行各种比较,java内置了Comparable接口,我们可以实现这个接口,然后进行比较,int,double等基础类型不能进行这样比较,必须使用其包装类Integer等。

Demo:

import java.awt.Shape;
class Student implements Comparable<Student>
{
    private String name;
    private int score;
    public Student(String name, int score) {
        super();
        this.name = name;
        this.score = score;
    }
    public int getScore() {
        return score;
    }

    @Override
    public int compareTo(Student o) {//o为所比较的对象
        if(o.getScore()<score)      //比较的条件
            return 1;               //符合返回1
        else
            return 0;               //不符合返回0
    }
    @Override
    public String toString() {
        return "Student [name=" + name + ", score=" + score + "]";
    }

}
public class CompareTo {

    public static <T> Comparable<T> findMax(Comparable<T>[] arr)
    {
        int maxIndex = 0;
        for (int i = 0; i < arr.length; i++) {
            if(arr[i].compareTo((T) arr[maxIndex])>0)//如果返回值大于0,则maxindex = i;
                maxIndex = i;
        }
        return arr[maxIndex];//最后返回最大的
    }
    public static void main(String[] args) {
    Integer[] in = {1,2,3,4,5,7,6};
    System.out.println(findMax(in));
    String [] st = {"Joe","Bob","Bill","ZZZZZ"};
    System.out.println(findMax(st));
    //  int [] s = {1,2,3,4,5,7,6};
    //System.out.println(findMax(s)); 
    //错误因为其只能用于实现了compare接口的类中
    Student[] stu = {new Student("one", 90),
                    new Student("two", 100),
                    new Student("three", 95)};
    System.out.println(findMax(stu));
    }
}

Result

7
ZZZZZ
Student [name=two, score=100]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值