![](/img/trans.png)
[英]Does lambda expression work as an implementation of abstract method of interface?
[英]does Lambda expression work on one interface?
Java 7
List<Person> personList = Person.createShortList();
// Sort with Inner Class
Collections.sort(personList, new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return p1.getSurName().compareTo(p2.getSurName());
}
});
Java 8
Collections.sort(personList, (Person p1, Person p2) ->
p1.getSurName().compareTo(p2.getSurName()));
for (Person p : personList) {
p.printName();
}
如果接口Comparator
有2種方法,而不僅僅是一種compare
,則可以使用Lambda嗎?
例如
public interface Comparator<T> {
int compare(T o1, T o2);
int compareTest(T o1, T o2);
}
功能接口僅需要一種抽象方法,而接口則不是這種方法。 但是,您可以為其中一種方法提供默認實現。 在這種情況下,它將起作用:
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
default int reverseCompare(T o1, T o2) {
return compare(o2, o1);
}
}
可以在需要實現功能接口的地方使用Lambda。 功能接口的定義在JLS§9.8中 :
功能接口是僅具有一個抽象方法(除
Object
的方法之外)的接口,因此表示單個功能協定。 這種“單一”方法可以采取多種抽象方法的形式,這些抽象方法具有從超級接口繼承的等效等效簽名。 在這種情況下,繼承的方法在邏輯上表示單個方法。
因此,在你的榜樣,沒有,如果有兩個抽象方法Comparator
( compare
和compareTest
),你不能使用Lambda實現它。
例如,這有效:
@FunctionalInterface
interface Foo {
void method1(int x);
}
public class Example {
public static final void main(String[] args) {
new Example().testFoo(x -> {
System.out.println(x);
});
}
private void testFoo(Foo f) {
for (int x = 0; x < 5; ++x) {
f.method1(x);
}
}
}
...但是如果我們添加到Foo
:
// WON'T COMPILE
@FunctionalInterface
interface Foo {
void method1(int x);
void method2(int x);
}
...它將不再編譯,因為它不再是功能接口。 (如果刪除了注釋,則該接口將[當然]進行編譯,但通過lambda對其進行使用則不會。)
請注意,我們可以向Foo
添加默認方法:
@FunctionalInterface
interface Foo {
void method1(int x);
default void method2(int x) {
// ...
}
}
可以,因為接口上只有一個抽象方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.