-2

In the code below I have a classic Java pass-by-value issue (written in processing; 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
}

Anyone have any clever tricks they use to assign a new object to a reference passed as a parameter?

I can describe my intent if needed, but I would love a generalized answer if one exists.

EDIT: Looks like I need to describe my intent. I'm using the Composite pattern to create a recursive hierarchy of objects. I have an object outside that hierarchy that I would like to reference one of the objects within the hierarchy. I would like to pass that object though the composite, Chain of Responsibility style, and then have that object reference whichever object took responsibility for it.

I can find a way to achieve this though return values I'm sure, but being able to assign the parameter I passed down the hierarchy would sure be nice if there's any cleaver way to do it.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Dukkha
  • 117
  • 1
  • 2
  • 9

2 Answers2

1

You can try returning the object of B that you create in class A4

Illustrated below.

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
        
        
    }
}

Output: B@7852e922

1

You can do this, but perhaps you need to provide a better description of what you want to achieve.

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
}
tgdavies
  • 10,307
  • 4
  • 35
  • 40