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:

  1. current.requiresupdate(newcat) //basically copy of equals() properties
  2. current.updatewith(newcat) //same above keeping old instance
  3. if (!current.name.euqals(newcat.name)) //for each property
  4. 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 2 cat objects equal if id, name , iq equal, implement equals method accordingly.
  • maintaining collection of cat objects: maintain collection of cat objects in there no 2 objects same id, use map<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

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -