`
tinggo
  • 浏览: 43936 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

对于JAVA中passed by reference & passed by value

    博客分类:
  • JAVA
阅读更多
虽然还是个在校学生,但是不管怎么说编程也有几个年头了。虽然JAVA学习的时间不长,但也有3/4个年头了。但是最近却被传引用还是传值的问题弄的困惑不已。先看下面的例子:
 public void badSwap(int var1, int var2)
{
  int temp = var1;
  var1 = var2;
  var2 = temp;
}


 public void tricky(Point arg1, Point arg2)
{
  arg1.x = 100;
  arg1.y = 100;
  Point temp = arg1;
  arg1 = arg2;
  arg2 = temp;
}
public static void main(String [] args)
{
  Point pnt1 = new Point(0,0);
  Point pnt2 = new Point(0,0);
  System.out.println("X: " + pnt1.x + " Y: " +pnt1.y); 
  System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
  System.out.println(" ");
  tricky(pnt1,pnt2);
  System.out.println("X: " + pnt1.x + " Y:" + pnt1.y); 
  System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);  
}               

运行结果如下
X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0

这样的结果着实让我很费解。
在查询了站内站外,国内国外后我将JAVA的这种现象用C++翻译了一下。
#include<iostream>
using namespace std;

class Point
{

public:
	Point(int a,int b){
		x=a;
		y=b;
	}
	int x;
	int y;
};

void badSwap(int *var1, int *var2)
{
  int *temp;
  temp= var1;
  var1 = var2;
  var2 = temp;
}

void tricky(Point *arg1, Point *arg2)
{
  arg1->x = 100;
  arg1->y = 100;
  Point *temp;
  temp= arg1;
  arg1 = arg2;
  arg2 = temp;
}

int main()
{
  Point *pnt1 = new Point(0,0);
  Point *pnt2 = new Point(0,0);
  cout<<"X: "<<pnt1->x<<"Y: "<<pnt1->y<<endl;
  cout<<"X: "<<pnt2->x<<"Y: "<<pnt2->y<<endl;
  cout<<endl;
  tricky(pnt1,pnt2);
  cout<<"X: "<<pnt1->x<<"Y: "<<pnt1->y<<endl;
  cout<<"X: "<<pnt2->x<<"Y: "<<pnt2->y<<endl;
  return 0;
} 


其实结果已经很明显。
虽然不知到java的具体语法是怎样实现的,如果使用C实现的话,猜想应该是这样的。
java: int a=5;  C++: int *a=5;
java: Point a=new Point(); C++: Point * a=new Point();
传递参数时
java: function(int a,int b) C++ function(int *a,int *b)
java: function(Point a,Point b) C++ function(Point *a,Point *b)


这样一来感觉自己在帮自己找麻烦,每次检查java代码时都要在脑中有一个指针的概念。
其实个人认为指针这东西很重要,因为它真实的反映了计算机内部的底层机制。虽然java封装了这一个特点,估计是因为很多人指针学的不好的缘故。但是对于我们这些指针用的还马马虎虎的人来说便成了个大问题。又是一个矛盾啊。就像市面上的框架一般虽然方便了编程,但是程序员越来越糊涂。这种对于要求逻辑和严谨的程序员可要不得。所以一定要挖清楚每一个细节。
其实如果要直观的理解这个特性其实也有方法,当然我还是使用C++的方法。
从今往后我会尽量少些这样的代码

public void function(Point p){
    Point tempP=p;
}

因为在C++中这样的代码翻译为:
void function(Point *p)
{
    Point *tempP;
    tempP=p;
}


显然在C++中这样的代码显得很没有意义(我个人经验认为)。


分享到:
评论
2 楼 HappyBlueCat 2009-10-25  
关于你的JAVA问题,提下我的看法:关于这方面,JAVA和C、C++确实有所不同。这关系到JAVA的内存回收。在JAVA中,如果直接有对象赋值的话,原来的对象就会被回收,而在C、C++中就不同。所以才会出现那样的问题。
1 楼 ZangXT 2009-08-05  
java的引用其实就是指针,不过在语言层面对它可以进行的操作进行了限制。
从说法上将,java的参数传递都是通过pass by value的方式实现的。
http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html

相关推荐

    条款20: 宁以pass-by-reference-to-const 替换 pass-by-value

    1、为什么要宁以pass-by-reference-to-const 替换 pass-by-value 效率方面 缺省情况下,C++以by value 方式传递对象至(或来自)函数。 除非你另外指定,否则函数参数都是以实际实参的副本为初值,而调用段所获得的...

    Java邮件开发Fundamentals of the JavaMail API

    Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Table of Contents If you're viewing this document online, you can click any of the topics below to link ...

    Dachs:Dachs; 小狗编程语言

    Otherwise, the argument is passed by reference then # immutable. Variable definition has the same rule as this. # Type of arguments and returned value are deduced automatically. # If you want to ...

    json.js_json2.js

    value&#41;; if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d;...

    delphi编译错误.txt

    Illegal reference to symbol ''''&lt;Name&gt;'''' in object file ''''&lt;Filename&gt;'''' 在对象文件中对符号的非法引用 Illegal type in OLE automation section: ''''&lt;typename&gt;'''' 在OLE自动区段中的非法类型 Illegal ...

    数位板压力测试

    16- and 32-bit API Reference By Rick Poyner Revised February 11, 2012 This specification was developed in response to a perceived need for a standardized programming inter-face to digitizing tablets...

    Google C++ Style Guide(Google C++编程规范)高清PDF

    Other C++ Features Reference Arguments Function Overloading Default Arguments Variable-Length Arrays and alloca() Friends Exceptions Run-Time Type Information (RTTI) Casting Streams Preincrement and ...

    php.ini-development

    directive because it is not set or is mistyped, a default value will be used. ; The value can be a string, a number, a PHP constant (e.g. E_ALL or M_PI), one ; of the INI constants (On, Off, True, ...

    servlet2.4doc

    The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. doGet...

    asp.net mvc

    In place of this property, the request context instance is passed to the protected virtual GetControllerInstance and GetControllerType methods. This change affects custom controller factories that ...

    tensorflow报错

    #TypeError: The value of a feed cannot be a tf.Tensor ... For reference, the tensor object was Tensor(“ArgMax:0”, shape=(64,), dtype=int64) which was passed to the feed with key Tensor(“Y:0”, dtype=i

    acpi控制笔记本风扇转速

    condition was removed by modifying AcpiWalkNamespace to (by default) ignore all temporary namespace entries created during any concurrent control method execution. An additional namespace race ...

    应用Dephi 开发佳能照相机API

    Calling this function releases all resources allocated by the libraries. This function delete all the reference or list objects that user has forgotten to delete. Parameters: In: None Out: ...

    多维时间序列记录库NetflixSpectator.zip

     The registry will keep a weak reference to the object passed  // in so that registration will not prevent garbage collection of the server object.  registry.methodValue(...

    BURNINTEST--硬件检测工具

    This will error faulty NICs that are not detected by the BurnInTest auto NIC detection mechanism. - Minor change to the 2D memory test when run with the 3D test (multiple large windows) and the ...

    VclZip pro v3.10.1

    Removed reference to QConsts, replaced with RTLConsts. Sometimes a GPF would result if a corrupt zip file was opened. Using a wildcard in pathname added to FilesList did not work. Using '*.*' as a ...

    WPTools.v6.29.1.Pro

    + the regular save and load methods (LoadFromFile, SaveToFile) can now access text wrapped by paired objects. specify the fieldname in the format string, i.e. "f:name=RTF" to save or load the ...

    eac3to V3.17

    * Blu-Ray subtitle demuxing: PTS value is now written to both PTS + DTS * joining MKV files is now declined with a proper error message * last chapter is now removed, if it's less than 10 seconds from...

    DevExpress VCL 13.2.5 D7-DXE6 FullSource

    •B254882 - TdxShellBreadcrumbEdit - Navigation to a valid path assigned to the edit value fails if the editor's Properties.ShellOptions.Root.BrowseFolder property is assigned a value other than ...

    stdafx.h代码

    // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes...

Global site tag (gtag.js) - Google Analytics