views:

88

answers:

2

I have two maps of type Map<Long, Integer>, one named "old" representing the old state of an object, and the other named "new" representing the new state of the same object.

Is there a simple & readable way of knowing if the old state and the new state are different (ie. if the state has changed)?

Ideally, I'd like some "java.utils" or "Apache Commons" library function like:

hasChanged = !MapUtils.diff(old, new).isEmpty();

Note: I looked for, but didn't find one.

Thanks.

+4  A: 

Doese'nt the equals method work?

Suraj Chandran
It depends on the implementation of the `equals()` method - hence my comment on the question. I would suspect it would on the implementation of the method.
Thomas Owens
It works, I need some sleep I guess. Thanks.
Sébastien RoccaSerra
+2  A: 

Equals seems like a bad idea because examining the entire map for equality sounds expensive. You also would need to lock both maps to do the check to make it threadsafe.

There's an idea used in ConcurrentHashMap where the map uses a counter to detect changes. If this were public you could just compare the counter in the 2 maps for equality. It's not, but you could accomplish the same thing with a dirty flag or possibly a class representing the object state that wraps the map and simplifies the equality checking.

Steve B.
You *need* to potentially examine the entire map for equality (in the equals case, at least) - what if the maps only differed in the last mapping you look at? Your counter comparison doesn't work either; they could be modified the same number of times, but with different values added (and the dirty flag doesn't work either for the same reason). The only way to check *is* to compare each name/value mapping.
Andrzej Doyle
@dtsazza: it seems to me that Steve's dirty flag could certainly be used to skip the full equals check in the case where neither has changed.
CPerkins
Thanks, that's interesting. In my case though, the maps are really small (ten elements or so), and shared once in a while by value over HTTP. So equals is just what I need.
Sébastien RoccaSerra