UnKnown UnKnown - 1 month ago 5
Java Question

How TableView and ListView's remove works?

As I saw we have to override

equals
and
hashCode
methods to remove Custom class's object from the java Collection's
java.util.List
or similar others.

But I want to know how the
TableView
and
ListView
's
remove
works? recently I successfully removed an custom class
(Person)
's object from the
TableView
's
ObservableList
( after viewing the
ObservableList
's
remove
method I realized it is inheriting the
remove(Object)
method from the
java.util.List
)

Then how it could be possible to remove the TableView's row by calling.
table.getItems().remove(row.getItem())
row contain Person class's object data and Person class didn't override
equals(object);
and
hashCode();
methods

Here is the complete code about this confusion.

public class RowMenu implements Callback<TableView<Person>, TableRow<Person>> {

@Override
public TableRow<Person> call(TableView<Person> table){
final TableRow row = new TableRow();
final ContextMenu contextMenu = new ContextMenu();
final MenuItem removeMenuItem = new MenuItem("Remove");
removeMenuItem.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println(row.getItem());
System.out.println(table.getItems().remove(row.getItem()));

}
});
contextMenu.getItems().addAll(removeMenuItem);
row.setContextMenu(contextMenu);
row.contextMenuProperty().bind(
Bindings.when(row.emptyProperty())
.then((ContextMenu)null)
.otherwise(contextMenu)
);
return row;
}
}

Answer

The default comparison just uses object identity; i.e. if you don't override equals(...) then object.equals(anotherObject) is equivalent to object == anotherObject.

In that case, list.remove(object) will remove a row from list if the reference object is identically equal to a reference held by the list.

In this case:

table.getItems().remove(row.getItem())

will clearly work. row.getItem() returns the item displayed by the table row, which is the very same object that is held in the table view's backing list of data. (The table view mechanism passes a reference from the table view's backing list to the table row's updateItem(...) method.)

You only need to worry about overriding equals if you want to supply an argument to remove(...) that is equal to the object you want to remove, but might not be a reference to the actual same object in memory.