java integer引用,如何增加类Integer从另一个方法引用java中的值

本文探讨了Java中Integer对象的值传递问题,为什么main方法中的n变量不会随着Increment方法中的递增操作而改变。通过实例解释了引用和值传递的差异,指出Integer类型是不可变的,导致n的值未受影响。同时介绍了可变对象如自定义MyIntegerObj的行为差异。
摘要由CSDN通过智能技术生成

package myintergertest;

/**

*

* @author Engineering

*/

public class Main {

/**

* @param args the command line arguments

*/

public static void main(String[] args) {

//this one does not increment

Integer n = new Integer(0);

System.out.println("n=" + n);

Increment(n);

System.out.println("n=" + n);

Increment(n);

System.out.println("n=" + n);

Increment(n);

System.out.println("n=" + n);

Increment(n);

//this one will increment

MyIntegerObj myInt = new MyIntegerObj(1);

Increment(myInt);

System.out.println("myint = " + myInt.get());

Increment(myInt);

System.out.println("myint = " + myInt.get());

Increment(myInt);

System.out.println("myint = " + myInt.get());

}

public static void Increment(Integer n) {

//NO. this doesn't work because a new reference is being assigned

//and references are passed by value in java

n++;

}

public static void Increment(MyIntegerObj n) {

//this works because we're still operating on the same object

//no new reference was assigned to n here.

n.plusplus(); //I didn't know how to implement a ++ operator...

}

}

The result for all of those is n=0. Integer n is an object and therefore passed by reference, so why isn't the increment reflected back in the caller method (main)? I expected output to be n=0 n=1 n=2 etc...

UPDATE:

Notice I updated the code example above. If I'm understanding correctly, Jon Skeet answered the question of why myInt would increment and why n does not. It is because n is getting a new reference assigned in the Increment method. But myInt does NOT get assigned a new reference since it's calling a member function.

Does that sound like I understand correctly lol ?

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值