问题
I have written following code to reverse the given String:
String str = "abcdef";
char[] strToChar = str.toCharArray();
char[] outString = new char[strToChar.length];
for(int j = 0; j < strToChar.length; ) {
int len = strToChar.length-j;
outString[j++] = strToChar[strToChar.length-j];
}
As per my understanding initialization happens from Right to Left. Hence, strToChar[strToChar.length-j]
here should throw ArrayIndexOutOfBoundException
.
But it runs fine. How is that happening? Shouldn't it evaluate to this?
outString[0] = strToChar[6]; //This should throw exception
回答1:
If I look at your code, then you have written your condition to be
for(int j = 0; j < strToChar.length;)
here strToChar.length will return you the actual length of the array which is 6.
The correct way to iterate an array with for loop would be:
for(int j = 0; j < strToChar.length;j++)
The index starting from 0 and going to < strToChar.length
回答2:
Acording to the java doc:
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
Which means j
is incremented before evaluating the right side of the expression.
So accordingly this code:
outString[j++] = strToChar[strToChar.length-j];
is evaluated to:
outString[0] = strToChar[6-1];
instead of:
outString[0] = strToChar[6-0];
来源:https://stackoverflow.com/questions/43494358/how-post-increment-operator-works-while-initialization