java中的方法引用


前言

这篇文章主要介绍什么是方法引用,以及方法引用的一些使用规则。(文章只是我个人的理解,如有问题欢迎指出)


一、什么是方法引用?

方法引用时jdk1.8之后引入的一种语法糖操作。作用是简化lambada在调用已经存在的方法时的表达式。

二、方法引用的几种类型

1.静态方法引用(类名::静态方法名)

代码如下:

public class Test {
    public static void main(String[] args) {
    
        ArrayList<Student> students = new ArrayList<>();
        students.add(new Student(10));
        
        // 类名::静态方法名 
        //注意事项:
        // 1.compare方法是静态的
        // 2.参数列表与 java.util.Comparator.compare(T o1, T o2) 参数列表保持一致
        students.sort(Student::compare);
    }

    static class Student {
        int age;
        public Student(int age) {
            this.age = age;
        }
        public int getAge() {
            return age;
        }
		//静态方法
        public static int compare(Student student1, Student student2) {
            return student1.getAge() - student2.getAge();
        }
    }
}

2.实例方法引用(对象名::实例方法名)

代码如下:

public class Test {
    public static void main(String[] args) {

        ArrayList<Student> students = new ArrayList<>();
        Student student = new Student(10);
        students.add(student);

        // 对象名::实例方法名
        //注意事项:
        // 1.compare方法是非静态的,方法由对象调用
        // 2.参数列表与 java.util.Comparator.compare(T o1, T o2) 参数列表保持一致
        students.sort(student::compare);


    }

    static class Student {
        int age;

        public Student(int age) {
            this.age = age;
        }

        public int getAge() {
            return age;
        }

        //对象方法
        public int compare(Student student1, Student student2) {
            return student1.getAge() - student2.getAge();
        }
    }
}

3.类的实例方法引用(类名::实例方法名)

代码如下:

 public static void main(String[] args) {

        ArrayList<Student> students = new ArrayList<>();
        Student student = new Student(10);
        students.add(student);

        // 类名::实例方法名
        //注意事项:
        // 1.compare方法是非静态的
        // 2.java.util.Comparator.compare(T o1, T o2) 参数列表中的第一个参数
        // 在compare方法中被省略(参数 o1 默认为调用者本身)
        students.sort(Student::compare)

    }

    static class Student {
        int age;
        public Student(int age) {
            this.age = age;
        }
        public int getAge() {
            return age;
        }
		//相比于java.util.Comparator.compare(T o1, T o2)接口参数,少了一个参数
        public int compare(Student student) {
            return this.getAge() - student.getAge();
        }
    }

总结

以上就是方法调用的使用。主要分为:静态方法引用,实例方法引用,类的实例方法引用。

  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值