Das JavaDoc für den ListChangeListener stellt eine Vorlage für das Behandeln von Änderungen bereit. Ich weiß jedoch nicht, wie ich mit Permutationen umgehen soll. Für jeden Index kann ich herausfinden, wo der neue Index des Artikels ist, aber ich weiß nicht, was ich damit machen soll. Dies ist ein kleines Puzzle, das unabhängig von der Programmiersprache ist. Eine ObservableList kann nur add(), remove(), set(), und hat auch einen Iterator.ListChangeListener wasPermutated-Block
Wenn ich eine ursprüngliche Liste [1,2,3] habe, und eine Liste [] an sie binden, muss die gebundene Liste [1,2,3] übereinstimmen. Wenn die ursprüngliche Liste den Komparator vertauscht, so dass die ursprüngliche Liste nun [3,2,1] lautet, wie mache ich die gebundene Liste mit?
/**
* Binds a source list's elements to a destination list. Any changes made in
* the source list will reflect in the destination list.
*
* @param <SRC> The source list's object type.
* @param <DEST> The destination list's object type.
* @param dest The destination list that will be bound to the src list.
* @param src The source list to watch for changes, and propagate up to the
* destination list.
* @param transformer A function that will transform a source list data
* type, A, into a destination list data type, B.
*/
public static <SRC, DEST> void bindLists(
ObservableList<DEST> dest, ObservableList<SRC> src, Function<? super SRC, ? extends DEST> transformer) {
/*Add the initial data into the destination list.*/
for (SRC a : src) {
dest.add(transformer.apply(a));
}
/*Watch for future data to add to the destination list. Also watch for removal
of data form the source list to remove its respective item in the destination
list.*/
src.addListener((ListChangeListener.Change<? extends SRC> c) -> {
while (c.next()) {
if (c.wasPermutated()) {
/*How do you handle permutations? Do you remove and then add,
or add and then remove, or use set, or use a copy arraylist
and set the right indices? Removing/adding causes concurrent modifications.*/
for (int oldIndex = c.getFrom(); oldIndex < c.getTo(); oldIndex++) {
int newIndex = c.getPermutation(oldIndex);
dest.remove(oldIndex);
dest.add(newIndex, dest.get(oldIndex));
}
} else if (c.wasUpdated()) {
} else {
/*Respond to removed data.*/
for (SRC item : c.getRemoved()) {
int from = c.getFrom();
dest.remove(from);
}
/*Respond to added data.*/
for (SRC item : c.getAddedSubList()) {
int indexAdded = src.indexOf(item);
dest.add(indexAdded, transformer.apply(item));
}
}
}
});
}
Ich würde auch gerne wissen, wie wasUpdated() selbst ausgelöst wird. Müssen die Objekte der ObservableList Observable oder etwas Ähnliches implementieren? –