simonides simonides - 1 year ago 148
Java Question

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

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

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

This is what I tried:


But eclipse states:

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

The List is declared as:

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

Answer Source

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

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

You can also explicitly specify the type of c:

listItems.addListener((ListChangeListener.Change<? extends Item> c) -> {/* ... */});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download