I am a Java noob. I have been able to grasp the concept of converting C/C++ pointers into Java references and this has gone fairly smoothly.
I hit a piece of code t
The only "pointer-like" method is unsafe() . You can allocate memory with it. But you cannot go outside the JVM area :)
A typical trick one could use to model pointers to pointers in Java is using arrays: a reference to the array itself serves as the "pointer", while the array element serves as the item pointed to. You can nest these as much as you'd like, but the code does not look nearly as nice as it does in C/C++.
Rather than porting C/C++ idioms into Java, you should build a mutable class that lets you change the item inside it. This class would serve as a "pointer" to give you the functionality that you are looking for, and it would also add readability to your Java code. Generics greatly simplify your task, requiring only one implementation that you could reuse.
Java doesn't have pointers. But one can say that when you create an Object
, you are creating a reference(pointer) to that Object
.
For example:
Object obj = new Object();
So the reference obj
is actually pointing to the new Object
you just created.
Now, if you want to translate the concept of pointer to a pointer, you could simply create a reference that would point to an existing reference.
Object obj = new Object();
Object obj2;
obj2 = obj;
Well pointer to pointer is not directly mappable in Java. I assume you want to assign a new object to a pointer inside a function.
As far as I know you can only solve this by using a wrapper object that acts as a reference, so you can modify the real reference inside:
class ObjRef {
public RealObj obj;
}
void modifyRef(ObjRef ref){
ref.obj = new RealObj()
}
Hope this helps
I'll answer my own question. I could not find any easy way to do a pointer to a pointer (reference to a reference) in java. So I refactored the code to use arrays of references, and array indices instead of pointers. I think this will work (it coded easily) but I have not tested it yet.