J'ai écrit le code suivant pour inverser la chaîne donnée:Comment fonctionne après l'opérateur ++ Increment tandis que l'initialisation
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];
}
Selon mon initialisation de compréhension se produit de droit-gauche. Par conséquent, strToChar[strToChar.length-j]
ici devrait jeter ArrayIndexOutOfBoundException
.
Mais ça marche bien. Comment cela se passe-t-il? Ne devrait-il pas évaluer cela?
outString[0] = strToChar[6]; //This should throw exception
, vous attribuez 'outString [0] = strToChar [6- 1] 'ici, ce qui n'entraînera aucune erreur. La clef ici est le 'j ++' qui conduira à la partie droite ne jette pas une exception, car la variable d'assignation gauche augmentera la valeur 'j' due au postincrement – SomeJavaGuy
Le [JLS] (https://docs.oracle .com/javase/specs/jls/se8/html/jls-15.html # jls-15.7) stipule: "Le langage de programmation Java garantit que les opérandes des opérateurs semblent être évalués dans un ordre d'évaluation spécifique, à savoir, depuis _left à droite_." – Thomas