Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/391.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java中指向同一数组的指针_Java_Pointers - Fatal编程技术网

Java中指向同一数组的指针

Java中指向同一数组的指针,java,pointers,Java,Pointers,我只是想确定我对这一点很清楚,因为我不太清楚确切的行为。我有两个阵列: private short[] bufferA; private short[] bufferB; 我想在两者之间交换。我可以这样做吗: private short[] currentBuffer; while(something) { currentBuffer = (condition) ? bufferA : bufferB; modify(currentBuffer); } private in

我只是想确定我对这一点很清楚,因为我不太清楚确切的行为。我有两个阵列:

private short[] bufferA;
private short[] bufferB;
我想在两者之间交换。我可以这样做吗:

private short[] currentBuffer;

while(something)
  {
  currentBuffer = (condition) ? bufferA : bufferB;
  modify(currentBuffer);
  }
private int currentBuffer;

while(something){
  currentBuffer = (condition) ? BUFFER_A : BUFFER_B;
  if(currentBuffer == BUFFER_A) {
    modify(bufferA);
  }else{
    modify(bufferB);
  }
}
要根据某些条件修改bufferA或bufferB,或者我应该使用标志并手动编写如下代码:

private short[] currentBuffer;

while(something)
  {
  currentBuffer = (condition) ? bufferA : bufferB;
  modify(currentBuffer);
  }
private int currentBuffer;

while(something){
  currentBuffer = (condition) ? BUFFER_A : BUFFER_B;
  if(currentBuffer == BUFFER_A) {
    modify(bufferA);
  }else{
    modify(bufferB);
  }
}

我正在使用的代码比这个简化的示例更复杂,因此如果我能用第一种方法来做,这将是我的首选。

您的第一个示例应该可以很好地工作。

是的,您可以。对数组的引用与任何其他引用一样。

第一种方法适用于数组(或任何其他容器)

但是,您不能重新分配变量,只需更改其内容:

int myVar = someCondition ? myInt1 : myInt2;
// this has no effect on either myInt1 or myInt2
myVar = 1000;
这里的原因是Java通过值传递一切,包括引用


因此,如果您将对容器的引用传递到其他地方,则该代码可以更改容器的内容,并且您的代码将看到这些更改。

两者都是allrite。。你可以走第一条路。。
<强> >:<强>作为一个旁注,java中的引用更像C++中的指针而不是C++中的引用。当然,java引用和C++指针之间仍然存在一些差异,例如C++中可以做指针运算。……/P > < P >。
所以参考资料是可行的

Java通过值原语和引用对象进行传递

乌多