How to determine if a variable has changed?

I found that I want to do certain things in my programs only if the variable has changed. I still did something like this:

int x = 1; int initialx = x; ...//code that may or may not change the value of x if (x!=initialx){ doOneTimeTaskIfVariableHasChanged(); initialx = x; //reset initialx for future change tests } 

Is there a better / easier way to do this?

+8
java
source share
6 answers

Since you want to find and perform some action only if the value changes, I would go with setXXX, for example:

 public class X { private int x = 1; //some other code here public void setX(int proposedValueForX) { if(proposedValueForX != x) { doOneTimeTaskIfVariableHasChanged(); x = proposedValueForX; } } } 
+5
source share

You can use getter / setter with the dirty bit associated with each field. mark it dirty if the value is changed using the installer, and force the user to use setters.

+4
source share

Another way is to use AOP to catch field changes, such as AspectJ, you can see http://www.eclipse.org/aspectj/doc/released/progguide/semantics-pointcuts.html

+4
source share

Example:

create a variable with the same name with number.

 int var1; int var2; if(var1 != var2) { //do the code here var2 = var1; } 

hope this help.

+2
source share

you can also use the concept of a flag, as when changing the value of x. set true to a boolean variable. The boolean value with the default value is false. check this way out.

This method is better than having getters and setters at the core of performance rather than having duplicate code from the two getters and seters methods.

0
source share

Assuming you have multiple threads, you can create an object monitor and wait for the changed object to wake up all blocked threads.

Something like that:

 private MyObject myObject; ... other thread ... while(true) { myObject.wait() logic you want to run when notified. } ... other thread ... ... later on ... myObject.change(); myObject.notifyAll(); 
0
source share

All Articles