This question already has answers here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
                                
                                    (14个回答)
                                
                        
                                2年前关闭。
            
                    
    @Test
    public void test(){
        Map<String, Integer> a = new HashMap<>();
        a.put("x", new Integer(0));
        Integer i = a.get("x");
        a.put("x", i++);
        i = a.get("x");
        a.put("x", i++);
        i = a.get("x");
        a.put("x", i++);
        System.err.println(i);
    }


上面代码的输出是1而不是0。我不知道为什么。有人可以解释发生了什么吗?
Java进行的一些字节代码优化导致这种状态?

最佳答案

因为i++在递增i之前返回i。看我的评论:

Map<String, Integer> a = new HashMap<>();
a.put("x", new Integer(0)); // x=0
Integer i = a.get("x");     // i=0
a.put("x", i++);            // x=0, i=1
i = a.get("x");             // i=0
a.put("x", i++);            // x=0, i=1
i = a.get("x");             // i=0
a.put("x", i++);            // x=0, i=1
System.err.println(i);


这是documentation of unary operators中的相关部分:


  可以在操作数(前缀)之前或之后(后缀)应用增量/减量运算符。代码result++;++result;都将导致结果加1。
  
  唯一的区别是前缀版本(++result)的值为增量值,而后缀版本(result++)的值为原始值。
  
  如果您只是执行简单的增量/减量,则选择哪个版本都没有关系。但是,如果在较大表达式的一部分中使用此运算符,则选择的运算符可能会产生很大的不同。

10-08 07:12
查看更多