简体   繁体   English

- - > - - Java中的运算符

[英]-​->-​- operator in Java

I was wondering, what does the -->-- operator do in Java? 我想知道, -->--运算符在Java中做了什么?

For example, if I have the following code: 例如,如果我有以下代码:

int x = 3;
int y = 3;
if (x -->-- y) {
    return true;
}

This always returns true. 这总是返回true。

Thank you! 谢谢!

In Java, -->-- is not actually an operator. 在Java中, -->--实际上不是运算符。

What you wrote is actually if ((x--) > (--y)) . 你写的实际上是if ((x--) > (--y))

And, as we know from this answer , the --y is predecrement, while the x-- is postdecrement, so therefore, this is basically if (3 > 2) , which always returns true . 而且,正如我们从这个答案中得知的那样, - y是预定义,而x--是后递减,因此,这基本上是if (3 > 2) ,它总是返回true

Positcrement and preicrement are very similar operators. Positcrement和preicrement是非常相似的运营商。 Java's bytecode gives a better understanding. Java的字节码可以更好地理解。 Each of them consists of two operations. 它们每个都包含两个操作。 Load variable and increment it. 加载变量并递增它。 The only difference is in the order of this operations. 唯一的区别在于此操作的顺序。 If statement from your case is compiled this way: 如果您的案例中的陈述是以这种方式编译的:

 4: iload_1               //load x
 5: iinc          1, -1   //decrement x
 8: iinc          2, -1   //decrement y
11: iload_2               //load y
12: if_icmple     23      //check two values on the stack, if true go to 23rd instruction

When JVM comes up to an if statement it has 3 and 2 on the stack. 当JVM出现在if语句中时,它在堆栈上有32 Line 4 and 5 are compiled from x-- . 第4行和第5行是从x--编译的。 Lines 8 and 11 from --y . 来自--y第8行和第11 --y x is loaded before increment and y after. x在递增之前加载, y在之后加载。

BTW, it's strange that javac does not optimize out this static expression. 顺便说一句,奇怪的是javac没有优化这个静态表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM