java - Comparing properties of objects that equal through an id -
lets assume there data service returns instances of class cat
:
class cat { int id; string name; int iq; }
i want hold instances inside set<cat>
must not hold 2 cats same id. need override equals
, hashcode
method check id
.
my question how can detect if cat inside set requires update when receive new instance service same id, different values name
and/or iq
? cannot add properties equals
or hashcode
since possible set holds instances of same id.
do have compare fields manually or there java-typical solution this?
edit clarification:
just updating set
new instance not enough because there code triggered on update. want is:
if (set.contains(newcat)) { cat current = set.get(newcat); if (!current.equals(newcat)) { //obviously not enough set.add(current); //notify eventbusses , such } }
solutions came mind are:
current.requiresupdate(newcat) //basically copy of equals() properties
current.updatewith(newcat) //same above keeping old instance
if (!current.name.euqals(newcat.name)) //for each property
- only objects service have changed. optimal, out of scope me.
all of require redundant code why hoping there pattern or collection work me.
the solution can include guava classes.
i think have 2 distinct problems:
- comparing
cat
objects: if 2cat
objects equal ifid
,name
,iq
equal, implementequals
method accordingly. - maintaining collection of
cat
objects: maintain collection ofcat
objects in there no 2 objects sameid
, usemap<integer, cat>
suggested.
your code may like:
if (mapofcats.contains(newcat.id)) { cat current = mapofcats.get(newcat.id); if (!current.equals(newcat)) { mapofcats.put(newcat.id, newcat); // notify eventbusses , such } }
Comments
Post a Comment