我应该知道这个,但为什么这会openPos[1]变为0?我知道它必须做与startPos[1] = 0在findCloseCurlBracket()方法,但为什么它做它没有意义.
int[] openPos = {1, 26};
System.out.println(openPos[0]+", "+openPos[1]);
int[] closePos = LuaTableParser.findCloseCurlBracket(stringList, openPos);
System.out.println(openPos[0]+", "+openPos[1]);
Run Code Online (Sandbox Code Playgroud)
findCloseCurlBracket()方法:
public static int[] findCloseCurlBracket(List<String> text, int[] openPos) {
int[] startPos = openPos;
int counter = 1;
for(int line = startPos[0]; line < text.size(); line++){
for(int index = startPos[1]; index < text.get(line).length()-startPos[1]; index++){
int[] curPos = {line, index};
if(getStringListCharAt(text, curPos) == '{'){
counter++;
}else if(getStringListCharAt(text, curPos) == '}'){
counter--;
}
if(counter == 0){
startPos[1] = 5;
return curPos;
}
}
startPos[1] = 0;
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
startPos如所指的在同一阵列openPos二者的事情是:引用到一个阵列的int第
int[] startPos = openPos;并没有采取的深层副本openPos.
您的写作startPos[1] = 5;正在更改openPos调用者中引用的同一数组中的元素findCloseCurlBracket.
深度复制的一种方法是写int[] startPos = openPos.clone();.
因为openPos是对(指向)数组的引用.您将该引用(不是数组,对它的引用)复制为findCloseCurlBracketas openPos.然后你将这个引用复制到startPos所以现在openPos变量,openPos参数和startPos变量都指向内存中的同一个数组:
+-------------------+
| openPos variable |--+
+-------------------+ |
|
+-------------------+ | +-----------+
| openPos argument |--+---->| the array |
+-------------------+ | +-----------+
| | 0: 1 |
+-------------------+ | | 1: 26 |
| startPos variable |--+ +-----------+
+-------------------+
然后你这样做:
startPos[1] = 5;
Run Code Online (Sandbox Code Playgroud)
...修改数组:
+-------------------+
| openPos variable |--+
+-------------------+ |
|
+-------------------+ | +-----------+
| openPos argument |--+---->| the array |
+-------------------+ | +-----------+
| | 0: 1 |
+-------------------+ | | 1: 5 |
| startPos variable |--+ +-----------+
+-------------------+
无论您使用什么引用,当您修改这些引用所指向的状态时,您都可以看到通过所有引用进行更改.
如果您不想共享阵列,则需要复制它,正如Bathsheba在她的回答(+1)中所示:
int[] startPos = openPos.clone();
Run Code Online (Sandbox Code Playgroud)