The properly implemented Object.equals is symmetric, meaning that there should be no difference between anObject.equals(element)
and element.equals(anObject)
.
You are describing a situation where the combobox model contains objects of type Item
, but you want to select select an item by specifying an object of type Prop
, where the value of Prop
describes some property of Item
.
Using technically incorrect implementation of equals()
method you can select a combobox item by passing an instance of Prop
instead of Item
.
With the original code, you will have to provide broken equals()
implementation in Prop
class, and with your modification you will have to provide broken equals()
implementation in Item
class. If the Prop
is some library class (as String
in your example) then the former case is, of course, impossible, and i assume that the reason for your proposed modification is to allow the latter case.
I am not sure that library creators tried to prevent programmers from implementing broken equals()
by choosing that specific anObject.equals(element)
expression, but even if it was element.equals(anObject)
it would still be bad practice to provide deliberately incorrect equals()
implementation just for the sake of simplifying the combobox selection.
The proper way to perform selection by property would be to search the combobox data for the item with the required properties or to create a completely new instance of Item
with the desired properties and then pass that item into the setSelectedItem
.
If you are lucky to already use Java 8 then selecting the required item from a list is one-liner, and if not then you will have to write some boilerplate code with cycle, but at least you will have the proper equals
implementation and clean conscience.