这几天学习android应用开发,遇到一个java基础问题,就是引用与赋值的概念区分
直接上代码分析:
类定义: public class Test { public int mA; public int mB; Test(int a, int b) { mA = a; mB = b; } } 赋值用法 测试代码: Test A = new Test(1,2); Test B = new Test(3,4); B.mA = A.mA; Log.i("Test", "the A a is :" + A.mA); Log.i("Test", "the B a is :" + B.mA); B.mA = 5; Log.i("Test", "the A a is :" + A.mA); Log.i("Test", "the B a is :" + B.mA);
测试结果:
the A a is 1
the B a is 1
the A a is 1
the B a is 5
引用用法 测试代码:
Test A = new Test(1,2); Test B = new Test(3,4); B = A Log.i("Test", "the A a is :" + A.mA); Log.i("Test", "the B a is :" + B.mA); B.mA = 5; Log.i("Test", "the A a is :" + A.mA); Log.i("Test", "the B a is :" + B.mA);
测试结果:
the A a is 1
the B a is 1
the A a is 5
the B a is 5
结论:
1. Java中除了基础类型,比如int long string等等这些参数传递的是值传递
2. 对象这些类型,参数传递的是引用传递
3. 参考网友说法 Test A只是声明了一个引用,并不是声明了一个对象; new Test() 才是定义了一个对象,“ = ” 对于类对象来说只是一个引用传递。
好吧 ~ 坑死了。对于C++的我来说很不适应Java,查找问题时候一直默认都是对象的拷贝,没想到是对象的引用,多花了两个小时查问题 ~
参考链接:https://www.cnblogs.com/2015android/articles/4719520.html