Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reference variables

I know Java does not permit pointers a la C++. However, I have heard something about references (presumably similar to C++ also). My question relates to the following problem:

I have a class "A", say, a bunch of which I instantiate (using new) in memory, and I wish to "link" these classes to one another depending on how I choose. In C++ I would just have a vector (defined in class A) of class A pointers to which I add pointers to the instances of class A I want to link to. This is basically like building an omnidirectional graph in memory (or unidirectional depending on how I construct my links)

My question is can I do this in Java in an elegant way, and how? I'm guessing it's something to do with references. Pointers seem such a simple solution to this problem, but I'm new to Java and learning how to do such things without pointers. I'm not really sure how to define a reference. In C++ I would have used the A * mypointer = new A();

Thanks,


1 Answers

import java.util.List;
import java.util.ArrayList;

class FunkyObject
{
    /** a list of other FunkyObject that this object is linked to */

    List<FunkyObject> referenceList = new ArrayList<FunkyObject>();

    /** creates a link between this object and someObject */

    public addRefrerence(FunkyObject someObject )
    {
        referenceList.add(a);
    }
}
like image 64
jahroy Avatar answered Dec 21 '25 18:12

jahroy