How to Increment a class Integer references value in java from another method

后端 未结 10 636
攒了一身酷
攒了一身酷 2020-12-09 02:29
package myintergertest;

/**
 *
 * @author Engineering
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void          


        
10条回答
  •  悲&欢浪女
    2020-12-09 03:26

    No, objects aren't passed by reference. References are passed by value - there's a big difference. Integer is an immutable type, therefore you can't change the value within the method.

    Your n++; statement is effectively

    n = Integer.valueOf(n.intValue() + 1);
    

    So, that assigns a different value to the variable n in Increment - but as Java only has pass-by-value, that doesn't affect the value of n in the calling method.

    EDIT: To answer your update: that's right. Presumably your "MyIntegerObj" type is mutable, and changes its internal state when you call plusplus(). Oh, and don't bother looking around for how to implement an operator - Java doesn't support user-defined operators.

提交回复
热议问题