简体   繁体   中英

Java ObservableArrayList not updated when adding to SortedSet

I have a SortedSet that is used as the parameter in an ObservableArrayList

public class MyListImpl
{
    SortedSet<Foto> fotos;
    ObservableList<Foto> observableFotos;

    public VerzamelingLijst() {
        fotos = new TreeSet<>();
        observableFotos = FXCollections.observableArrayList(fotos);
    }

    @Override
    public boolean add(Foto object) {
        try {
            return fotos.add(object);
        } catch (NullPointerException e) {
            return false;
        }
    }

    @Override
    public ObservableList<Foto> getReadOnlyList() {
        return observableFotos;
    }
}

In my unittest I check if there is an ObservableList is returned, and if an item is added when using the add() method.

@Test
public void testGetReadOnlyList() {
    ObservableList<Foto> result = instance.getReadOnlyList();
    assertThat(result, instanceOf(ObservableList.class));

    instance.add(foto1);
    assertFalse(result.isEmpty());
}

When I run this test method, assertFalse fails because foto1 is not added to the ObservableList, but when I first add foto1, and then get the ObservableList, the assertFalse succeeds.

It is my assumption that the contents of an ObservableList is updated when an object is added to the container that was passed in as a parameter.

What is going on here and can I do to get this working?

If you read the documentation, you would notice that FXCollections.observableArrayList specifically says it creates a new list. If you want your changes to be visible to listeners, you must use this new list to make your changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM