Can I make an array of variables in Java?

fil :

Based on another setting, I have a list of variables that need to be set to elements of an array. How can I make this succinct, without pointers?

Example: I have a string with chess moves and variables startRow, startCol, endRow, endCol, color, piece (all strings).

The data comes from a string which I split into String[] bits.

But if the associated type is "A" then the string is

startRow, startCol, endRow, endCol, color, piece

but if the type is "E" then the string is

piece, color, startRow, endRow, startCol, endCol

I have variables of the same names. I can do

case "A":
    startRow = bits[0];
    startCol = bits[1];
    (etc)
case "E":
    startRow = bits[2];
    startCol = bits[4];
    (etc)

But I'd like

Vars[] av = {startRow, startCol, endRow, endCol, color, piece};
Vars[] ev = {piece, color, startRow, endRow, startCol, endCol};

and set Vars[] allv to either one and loop:

allv[i] = bits[i];

C (or PHP) is not an option!

Nick :

If startRow, startCol, etc. are fields (as opposed to local variables), you can write an anonymous function for each field that has the behavior of assigning the value of its argument to the field.

E.g.

List<Consumer<String>> aSetters =
  Arrays.asList(
    s -> startRow = s,
    s -> startCol = s,
    s -> endRow = s,
    s -> endCol = s,
    s -> color = s,
    s -> piece = s);

List<Consumer<String>> eSetters =
  Arrays.asList(
    s -> piece = s,
    s -> color = s,
    s -> startRow = s,
    s -> startCol = s,
    s -> endRow = s,
    s -> endCol = s);

List<Consumer<String>> setters; // initialize to aSetters or eSetters accordingly

for (int i = 0; i < bits.length; i++) {
  setters.get(i).accept(bits[i]);
}

An alternative to using the anonymous functions s -> color = s is to use a method reference to the setter for that field, if one is available (e.g. this::setColor).

If startRow, etc. are local variables, there isn't really a good way to do this because Java doesn't let you assign to local variables from anonymous functions. There are some nasty hacks, like replacing each variable with an array of length 1 and assigning to the 0th element of the array from the anonymous function, which is allowed, but this can be very confusing to read.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=157584&siteId=1