终于搞清楚了:java8的接口为什么新增default,为了Lambda服务
要用lambda表达式或者为了更好的推广Lambda表达式,要求接口,有且只有一个抽象方法abstract,就是函数式接口(也可以加上注解来约束,@FunctionalInterface,多写或者少写会报错,Object的方法如equals等特殊不计算),那么接口原有其他方法就需要有个默认实现。
如comparator接口有多个方法,而Lambda比较大小只用到其他一个方法( lists.stream().sorted((a,b)->{return a;});),不需要实现其他方法,那么其他方法不需要被实现就需要有默认实现,这时就新增了default语法。
@FunctionalInterface
interface HelloLa2{
int sayHello(int a);
}
class client{
public static void main(String[] args) {
HelloLa2 l2=(a)->a+666;
l2.sayHello(111);
}
为了让lambda使用更广泛,如comparator等接口,需要改造为只有一个抽象方法的接口,哪个其他方法需要有default来实现。
List<Long> ss= Lists.newArrayList(1L,2L,3L);
ss.stream().sorted(Comparator.comparing(aLong -> {return aLong;}));
ss.stream().sorted((a,b)->{return a;});
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
default Comparator<T> reversed() {
return Collections.reverseOrder(this);
}
default Comparator<T> thenComparing(Comparator<? super T> other) {
Objects.requireNonNull(other);
return (Comparator<T> & Serializable) (c1, c2) -> {
int res = compare(c1, c2);
return (res != 0) ? res : other.compare(c1, c2);
};
}