jdk8新特性:方法引用

  • 作用:进一步进化laambda
  • 是什么:方法的引用,方法引用的标志性符号: “::”

1静态方法的引用

1.1 为什么学

  • 这个后面spring引用挺多的
  • 静态方法不用创建对象,

怎么学

这个方法引用难学,现在有印象就行,将来遇到了再回来回顾,写代码的时候发现可以用方法引用简化再使用(面向结果编程)
在这里插入图片描述

1.2原来代码

package com.ruoyi.project;

public class CompareByDate {

    public  static int compareByAge(Student o1,Student o2){
        return  o1.getAge()-o2.getAge();
    }
}
package com.ruoyi.project;


import java.util.Arrays;


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

        Student student1 = new Student("小1", 160.1, 13);
        Student student2 = new Student("小2", 189.3000000002, 77);
        Student student3 = new Student("小3", 189.3000000001, 43);

        Student students[] = {student1, student2, student3};
		// Arrays.sort(students, (o1, o2) -> o1.getAge()-o2.getAge();
        Arrays.sort(students, (o1, o2) -> CompareByDate.compareByAge(o1, o2));

      
        System.out.println(Arrays.toString(students));

    }
}

1.3静态方法引用

package com.ruoyi.project;


import java.util.Arrays;


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

        Student student1 = new Student("小1", 160.1, 13);
        Student student2 = new Student("小2", 189.3000000002, 77);
        Student student3 = new Student("小3", 189.3000000001, 43);

        Student students[] = {student1, student2, student3};
	// Arrays.sort(students, (o1, o2) -> o1.getAge()-o2.getAge();
    //    Arrays.sort(students, (o1, o2) -> CompareByDate.compareByAge(o1, o2));
        Arrays.sort(students, CompareByDate::compareByAge

       
        System.out.println(Arrays.toString(students));

    }
}
  • 以上两种方法 运算结果都为
  • 在这里插入图片描述

2 实例方法的引用

和静态方法区别:这个有创建实例

package com.ruoyi.project;
import java.util.Arrays;
public class Test {
    public static void main(String[] args) {

        Student student1 = new Student("小1", 160.1, 13);
        Student student2 = new Student("小2", 189.3000000002, 77);
        Student student3 = new Student("小3", 189.3000000001, 43);
        Student students[] = {student1, student2, student3};

//降序
        CompareByDate compareByDate=new CompareByDate();
        Arrays.sort(students, compareByDate::compareByAgeDesc);
        System.out.println(Arrays.toString(students));

    }
}
package com.ruoyi.project;

public class CompareByDate {

    public static int compareByAge(Student o1, Student o2) {
        return o1.getAge() - o2.getAge();
    }

    //降序
    public int compareByAgeDesc(Student o1, Student o2) {
        return o2.getAge() - o1.getAge();
    }


}

3特定类型方法的引用

在这里插入图片描述
在这里插入图片描述

4构造器引用

开发中使用场景不常用到,代码没有实际意义,关注语法

在这里插入图片描述

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值