idea 进入方法实现类 mac_Java里面实现类之间的比较的两种方法

本文介绍了在Mac环境下,使用IntelliJ IDEA(Idea)快速定位到Java方法实现类的两种方法,帮助开发者高效地进行代码浏览和调试。
摘要由CSDN通过智能技术生成
1 方法1:实现Comparable接口
package yangzp.compareable;

/**
 * @author yzp
 */
public class ComparableTest {
//在这会报错,因为我传入的不是同一类型的两个类
//我在下边抛出了错误 throw
    public static void main(String[] args) {
        Student s = new Student("yzp",20);
        Object h =  new Object();
        Object o = new Student("kk",20);
        System.out.println(s.compareTo(h));
    }
}

class Student implements  Comparable{
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
///。。。。。。。。此处省略了Get And Set。。。。//
    @Override
    public int compareTo(Object o) {
            if (o instanceof Student){
                return this.getAge() - ((Student) o).getAge();
            }
            throw new RuntimeException("该类型不是Student");
    }
}

205354cfa1ef040b3aa3f899581ac900.png

2 方法2 给sort(函数)或者equal函数传入Comparator类
package yangzp.compareable;
import java.util.*;

/**
 * @author yzp
 */
public class ComparatorTest {

    public static void main(String[] args) {
        Goods[] goods = new Goods[5];
        goods[0] = new Goods("Coke",30);
        goods[1] = new Goods("XueBi",2);
        goods[2] = new Goods("FenDa",41);
        goods[3] = new Goods("TeLunSu",53);
        goods[4] = new Goods("YiLi",24);
        Arrays.sort(goods,a);
        System.out.println(Arrays.toString(goods));
    }
    private static Comparator a = new  Comparator(){
        @Override
        public int compare(Object o, Object t1) {
            if (o instanceof Goods && t1 instanceof Goods){
                return  (((Goods) o).getPrice() - ((Goods) t1).getPrice());
            }
            throw new RuntimeException("传入数据类型不一致");
        }
    };
}


class Goods{
    private String name;
    private int price;

    public Goods(String name, int price) {
        this.name = name;
        this.price = price;
    }
///。。。。。。。。此处省略了Get And Set。。。。//
    @Override
    public String toString() {
        return "Goods{" +
                "name='" + name + ''' +
                ", price=" + price +
                '}';
    }
}

5d9c61aaafcd14310506e4230c02319c.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值