Pointers to the same array in Java
I just want to make sure I'm clear on this, as I'm not quite sure of the exact behavior. I have two arrays:
private short[] bufferA;
private short[] bufferB;
which I want to swap between. Can I do something like this:
private short[] currentBuffer;
while(something)
{
currentBuffer = (condition) ? bufferA : bufferB;
modify(currentBuffer);
}
to modify the bufferA or bufferB depending on some condition, or should I use flags and manually code it like this:
private int currentBuffer;
while(something){
currentBuffer = (condition) ? BUFFER_A : BUFFER_B;
if(currentBuffer == BUFFER_A) {
modify(bufferA);
}else{
modify(bufferB);
}
}
The code I'm working with is more complex than this simplified example, so if I can do it th开发者_高级运维e first way that would be much preferred.
Although your arrays are holding primitives, Arrays itself are objects
- http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html#12028
so reference works ok.
Java passes by value primitives, and by reference objects.
Udo
Yes you can. References to arrays are like any other references.
Your first example should work fine.
The first way will work just fine with arrays (or any other containers).
However, you can not reassign variables, just change their contents:
int myVar = someCondition ? myInt1 : myInt2;
// this has no effect on either myInt1 or myInt2
myVar = 1000;
The reason here is that Java passes everything by value, including references.
So if you pass a reference to a container somewhere else, that code can change the container's content and your code will see the changes.
Both are allrite.. you can go ahead with the 1st way.. EDIT: as a side note, references in java are more like pointers in c++ than references in c++. course there still are some differences between java references and c++ pointers e.g. u can do pointer arithmetic in c++..
精彩评论