【问题标题】:Creating an array of variables whose values can be modified创建一个可以修改其值的变量数组
【发布时间】:2020-03-20 10:29:41
【问题描述】:

我想要类似的东西:

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

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

这样的结果应该是我原来的x变量的值应该变成5了。

在 Java 中可以使用这样的变量数组吗?

【问题讨论】:

  • 在 Java 中不可能。你想要 C++ 引用之类的东西。 Java 没有。
  • @khelwood 是的,类似于 C++ 参考,该死的......谢谢你的回答
  • 为什么 x=5 而不是 4?

标签: java arrays pointers reference


【解决方案1】:

对象可能有类似(不完全一样)的东西:

如果你有一个 Number 类:

class Number {
    int value;

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

你尝试过这样的事情:

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

否则,materials[0] = something 只会替换数组中的第一个元素。

【讨论】:

  • 哇,这很有帮助,谢谢你,我真的很感谢你的解决方案。
猜你喜欢
  • 2020-06-25
  • 2017-03-23
  • 2021-11-03
  • 2018-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-30
  • 1970-01-01
相关资源
最近更新 更多