Regarding pointers in Java

I’m having a bit of an organizational issue (read: a mess) in my code. Often objects within a data structure need to reference other objects from the same or other data structures. For example, a Player object might need to reference the Sprite object as well as the Level object.

So fair I’ve been using integers that point to globally accessible arrays containing all the items. This, of course, irks me, specially because of the many global arrays that need to be defined at compile time.

In C++ I’d go pointer crazy, having items hold a pointer, defined at runtime, to whatever item/structure I need.

As far as I understand it, technically an object instance in Java is a pointer, and, as such, assigning existing instances to inner pointers within the “child” objects would be a way to do this, right?

Example:



// .... Parent Class

public class Parent
{
     private int childAllowance = 0;

     public void setAllowance(int value) { this.childAllowance = value; }
     public int   getAllowance()            { return this.childAllowance; }
}

// .... Global Array containing all the existing Parent Objects

public static Parent[] parentArray = new Item[]{ new Parent(), new Parent(), ... };

// .... Child Class

public class Child
{
     public Parent parent = null;

     public Child(Parent parent)
     {
          this.parent = parent;
      }

      public void getAllowance()
     {
           System.out.println("Obtains " +parent.getAllowance()+ " coin from Parent!");
      }
}

// ..... Main execution code

parentArray[x].setAllowance(10);

Child Jhonny = new Child(parentArray[x]);
Child Susie   = new Child(parentArray[x]);

Jhonny.getAllowance(); // "Obtains 10 coin from Parent!"
Susie.getAllowance(); // "Obtains 10 coin from Parent!"

parentArray[x].setAllowance(20);

Susie.getAllowance(); // "Obtains 20 coin from Parent!"
Jhonny.getAllowance(); // "Obtains 20 coin from Parent!"

Susie.parent.setAllowance(100);
Susie.getAllowance(); // "Obtains 100 coin from Parent!"
Jhonny.getAllowance(); // "Obtains 100 coin from Parent!"

System.out.println("Parent at X is giving " +parentArray[x].getAllowance()+ " coin to it's children"); // "Parent at X is giving 100 coin to it's children"



So this would result in both Child objects having a reference to the same Parent object held in the Array? Rather than making a clone, I mean, so if another part of the program modifies said object, the Child objects will see the change too.

And this, I guess, means that the object will not be lost as long as a reference exists, so the GC won’t get crazy there.

Is this approach to have objects held in a centralized container class valid? Is there a massive caveat I’m not seeing? Because maintaining the array indices for the many objects is becoming a burden.