Reputation:
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,
Upvotes: 3
Views: 398
Reputation:
Thanks for all your help - it has been very useful. It seems references provide the elegant solution I was looking for, which pointers offer in C/C++. The only main difference I can see so far (without actually implementing) is that we cannot perform arithmetic on references.
Upvotes: 0
Reputation: 22692
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);
}
}
Upvotes: 4
Reputation: 36532
You can think of references as pointers since they refer to the instance just as a pointer points to a memory location. The big difference is that Java doesn't allow arithmetic on references as C does on pointers. You also cannot create a reference to a field--only to an object and only by instantiating it with new
.
As for storing references to several instances of A
, you have many options. You can use a List
such as ArrayList
or any of the other Collection
classes. It really depends on how you need to access them. Peruse through the java.util
package for all of the collections.
Upvotes: 0
Reputation: 39950
What you described in the second paragraph is pretty much exactly how Java's model works. (It's also the only way it works.) When Java tutorials say that "Java is pass-by-value", the values they mean are primitive types, and object handles. That is, when you pass an object-typed value around, the object doesn't get copied. (Which I believe is the same behaviour as passing a pointer to a struct around in C.)
What you, for instance, can not do is create a pointer pointing to a local variable or object field. You can only pass around their values.
Upvotes: 0
Reputation: 10988
public class A {
private A[] refs;
public A(A... refs) {
this.refs = refs;
}
}
Upvotes: 1