【问题标题】:How do I change the value of object after passing parameter in Java? [duplicate]在Java中传递参数后如何更改对象的值? [复制]
【发布时间】:2021-08-25 21:05:42
【问题描述】:

我刚开始学习 Java,我想到的是它们不像 c++ 那样通过引用传递。将对象变量传递给函数后如何更改它的值?

public static doStuff(Node x, Node currentNode){
   if(x == null)
      x = currentNode;

}

public static void main(String []args) {
   Node x = null;
   Node newNode = new Node() 
   doStuff(x,newNode);
   System.out.println(x) // --> This one supposed to be different than null

}

【问题讨论】:

  • 在 Java 中传递对象变量类似于在 C 或 C++ 中传递指针。您无法更改它所引用的 哪个 对象,但您可以 更改它所引用的对象的字段。因此,您可能会尝试编写一个具有您想要更改的值作为其字段之一的类。

标签: java function object reference


【解决方案1】:

这是 Java 的一个奇怪的限制。

我相信您所描述的模式的预期模式是修改“doStuff”方法以返回 currentNode,然后在 main 中设置值。

类似:

public static Node doStuff(Node x, Node currentNode){
   if(x == null) {
      return currentNode;
    }
}

public static void main(String []args) {
   Node x = null;
   Node newNode = new Node() 
   x = doStuff(x,newNode);
   System.out.println(x) // --> This one supposed to be different than null

}

我参考了这个答案来创建我的:

参考:Java changing value of a variable through a method?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多