Java 如何使用 lambda 编写新的 ListChangeListener<Item>()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23335522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:00:27  来源:igfitidea点击:

How do I write a new ListChangeListener<Item>() with lambda?

javalambdalistenerjava-8changelistener

提问by simonides

How do I write a new ListChangeListener() with lambda in java8?

如何在 java8 中使用 lambda 编写新的 ListChangeListener()?

listItems.addListener(new ListChangeListener<Item>() {
    @Override
    public void onChanged(
        javafx.collections.ListChangeListener.Change<? extends Item> c) {
        // TODO Auto-generated method stub
    }
});

This is what I tried:

这是我尝试过的:

listItems.addListener(c->{});

But eclipse states:

但日食指出:

The method addListener(ListChangeListener) is ambiguous for the type ObservableList.

方法 addListener(ListChangeListener) 对于 ObservableList 类型是不明确的。

The List is declared as:

该列表声明为:

ObservableList<Item> listItems = FXCollections.observableArrayList();

采纳答案by Andrew Vitkus

Since ObservableListinherits addListener(InvalidationListener)from the Observableinterface, the compiler is unable to determine which version to call. Specifying the type of the lambda through a cast should fix this.

由于从接口ObservableList继承,编译器无法确定调用哪个版本。通过强制转换指定 lambda 的类型应该可以解决这个问题。addListener(InvalidationListener)Observable

listItems.addListener((ListChangeListener)(c -> {/* ... */}));

You can also explicitly specify the type of c:

您还可以明确指定的类型c

listItems.addListener((ListChangeListener.Change<? extends Item> c) -> {/* ... */});

回答by dmolony

This code works without having to specify the types.

此代码无需指定类型即可工作。

listView.focusedProperty ().addListener ( (arg, oldVal, newVal) -> System.out
        .printf ("ListView %s focus%n", (newVal ? "in" : "out of")));