本文介绍了Java8 Lambdas与匿名类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于最近发布了Java8并且其全新的lambda表达式看起来非常酷,我想知道这是否意味着我们习以为常的匿名类的消亡。

Since Java8 has been recently released and its brand new lambda expressions looks to be really cool, I was wondering if this means the demise of the Anonymous classes that we were so used to.

我一直在研究这个问题,并找到了一些关于Lambda表达式如何系统地替换这些类的很酷的例子,例如Collection的sort方法,它用于获取Comparator的Anonymous实例来执行排序: / p>

I've been researching a bit about this and found some cool examples about how Lambda expressions will systematically replace those classes, such the Collection's sort method, which used to get an Anonymous instance of Comparator to perform the sort:

Collections.sort(personList, new Comparator<Person>(){
  public int compare(Person p1, Person p2){
    return p1.firstName.compareTo(p2.firstName);
  }
});

现在可以使用Lambdas完成:

Now can be done using Lambdas:

Collections.sort(personList, (Person p1, Person p2) -> p1.firstName.compareTo(p2.firstName));

看起来非常简洁。所以我的问题是,有没有理由继续在Java8中使用这些类而不是Lambdas?

And looks surprisingly concise. So my question is, is there any reason to keep using those classes in Java8 instead of Lambdas?

编辑

同样的问题,但在相反的方向,使用Lambdas而不是匿名类有什么好处,因为Lambdas只能用于单个方法接口,这个新功能只是一个仅用于少数几个的快捷方式或者它真的有用吗?

Same question but in the opposite direction, what are the benefits of using Lambdas instead of Anonymous classes, since Lambdas can only be used with single method interfaces, is this new feature only a shortcut only used in few cases or is it really useful?

推荐答案

匿名内部类(AIC)可用于创建抽象类的子类或具体的课程。 AIC还可以提供接口的具体实现,包括添加状态(字段)。可以在其方法体中使用 this 来引用AIC的实例,因此可以在其上调用其他方法,其状态可以随时间变化,等等。这些适用于lambdas。

An anonymous inner class (AIC) can be used to create a subclass of an abstract class or a concrete class. An AIC can also provide a concrete implementation of an interface, including the addition of state (fields). An instance of an AIC can be referred to using this in its method bodies, so further methods can be called on it, its state can be mutated over time, etc. None of these apply to lambdas.

我猜大多数AIC的用途是提供单个函数的无状态实现,因此可以用lambda表达式替换,但是是不能使用lambda的AIC的其他用途。 AIC即将停留。

I'd guess that the majority of uses of AICs were to provide stateless implementations of single functions and so can be replaced with lambda expressions, but there are other uses of AICs for which lambdas cannot be used. AICs are here to stay.

更新

AIC与lambda之间的另一个区别表达式是AIC引入了一个新的范围。也就是说,名称是从AIC的超类和接口中解析出来的,并且可以影响在词汇封闭环境中出现的名称。对于lambdas,所有名称都是词法解析的。

Another difference between AICs and lambda expressions is that AICs introduce a new scope. That is, names are resolved from the AIC's superclasses and interfaces and can shadow names that occur in the lexcially enclosing environment. For lambdas, all names are resolved lexically.

这篇关于Java8 Lambdas与匿名类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 01:21