问题
Assume that I have defined two arrays in Java. The first array has m
cells and the second has n
cells. Assume that each cells can have a 0
or 1
value.
In this program every cell of the first array will join one of the cells of the second array, but we do not know which one will be connected to which cell of the second array (This connection is totally logical,e.g. we just know array1[3]
is related to array2[7]
).
So now I want to define an event handler for each of these relationship, so when one of the cells fluctuate from 1 to 0, its paired cell fluctuate. Actually I want to define event handler in a run-time and in dynamic way, because before it, I do not know which one of the cells in array1
will be pair with which one of cells in array2
.
Is there any solution for this?
If you think I can solve this problem without dynamic event handler please let me know about your solution.
回答1:
Here's a way to solve this without using an event handler. See if this works for what you are doing.
First, instead of two arrays, let's use two 2D arrays that are m x 1
and n x 1
.
int[][] array1 = new int[m][];
int[][] array2 = new int[n][];
for (int i = 0; i < m; i++)
array1[i] = new int[] { /* your code */ ? 1 : 0 };
for (int i = 0; i < n; i++)
array2[i] = array1[ /* your code */ ];
The first /* your code */
is your condition for choosing to put either 1
or 0
into each element of array1
. The second /* your code */
is your method for deciding which element of array1
corresponds to each element of array2
.
Now each element in array2
is also an element of array1
, so when you update a value in one of the arrays from 0
to 1
, it is also updated in the other array.
array2[7] = array1[3];
array1[3][0] = 0;
System.out.println(array2[7][0]); // prints "0"
array1[3][0] = 1;
System.out.println(array2[7][0]); // prints "1"
来源:https://stackoverflow.com/questions/19839758/define-dynamically-event-handler-in-java