Increment a Integer's int value?

前端 未结 9 2086
你的背包
你的背包 2020-12-14 05:11

How do I increment a Integer\'s value in Java? I know I can get the value with intValue, and I can set it with new Integer(int i).

playerID.intValue()++;
         


        
9条回答
  •  离开以前
    2020-12-14 05:44

    As Grodriguez says, Integer objects are immutable. The problem here is that you're trying to increment the int value of the player ID rather than the ID itself. In Java 5+, you can just write playerID++.

    As a side note, never ever call Integer's constructor. Take advantage of autoboxing by just assigning ints to Integers directly, like Integer foo = 5. This will use Integer.valueOf(int) transparently, which is superior to the constructor because it doesn't always have to create a new object.

提交回复
热议问题