Creating an array of variables whose values can be modified

Fábio Morais :

I want something like:

this.x=4;
this.y=5;
this.materials = [this.x, this.y];

this.materials[0]=5;//this will change the x variable

The result of this should be that the value of my original x variable should become 5.

Is such an array of variables possible in Java?

flaviuratiu :

Something similar (not exactly like that) is possible with objects:

If you had a Number class:

class Number {
    int value;

    Number(int value) {
        this.value = value;
    }
}

And you tried something like this:

Number x = new Number(4);
Number y = new Number(5);
Number[] materials = {x, y};

materials[0].value = 5; 
// the value property of the first number object in the array 
// (same as referenced by x) became 5

Otherwise, materials[0] = something would just replace the first element in the array.

Guess you like

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