【问题标题】:Any tips on getting around the pass-by-value issue?有关解决按值传递问题的任何提示?
【发布时间】:2021-03-24 01:53:02
【问题描述】:

在下面的代码中,我遇到了一个经典的 Java 值传递问题(写在处理中;setup() == main)。

void setup()
{
  A a = new A();
  
  a.makeTheB(a.b);
  System.out.println(a.b); //Returns null
}

class A
{
  B b;
  
  public void makeTheB(B tempB)
  {
    tempB = new B();
  }
}

class B
{
  float x; //not used
}

谁有什么巧妙的技巧可以将新对象分配给作为参数传递的引用?

如果需要,我可以描述我的意图,但如果存在,我希望有一个笼统的答案。

编辑:看起来我需要描述我的意图。 我正在使用复合模式来创建对象的递归层次结构。我在该层次结构之外有一个对象,我想引用该层次结构中的一个对象。我想通过复合的责任链样式传递该对象,然后让该对象引用负责它的任何对象。

虽然我确定返回值,但我可以找到一种方法来实现这一点,但是如果有任何更简单的方法可以分配我传递给层次结构的参数,那肯定会很好。

【问题讨论】:

  • 返回一个值而不是void?
  • 在 A 构造函数中创建 B 并将其分配给字段。如果由于某种原因你不能这样做,请在 A 上创建一个 setter。

标签: java parameters parameter-passing pass-by-reference pass-by-value


【解决方案1】:

您可以尝试返回您在类A4 中创建的B 的对象

如下图所示。

public class A {

    B b;

    public B makeTheB(B tempB) {
        tempB = new B();
        return tempB;
    }
}

public class B {
    float x; //not used
}

public class Test {

    public static void main(String[] args) {
        A a = new A();

        B b = a.makeTheB(a.b);
        System.out.println(b); //Returns nu
        
        
    }
}

输出:B@7852e922

【讨论】:

    【解决方案2】:

    您可以这样做,但也许您需要更好地描述您想要实现的目标。

    void setup()
    {
      A a = new A();
      
      a.makeTheB(a);
      System.out.println(a.b);
    }
    
    class A implements Consumer<B>
    {
      B b;
    
      public void accept(B b) {
        this.b = b;
      }
      
     /**
      * Create a B, and give it to a Consumer which knows where it needs to be stored.
      */
      public void makeTheB(Consumer<B> consumer)
      {
        consumer.accept(new B());
      }
    }
    
    class B
    {
      float x; //not used
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-29
      • 2020-10-02
      • 2016-07-30
      • 2019-01-20
      • 1970-01-01
      • 2020-05-18
      • 2019-10-29
      • 1970-01-01
      相关资源
      最近更新 更多