`
tinggo
  • 浏览: 44731 次
  • 性别: 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 方式传递对象至(或来自)函数。 除非你另外指定,否则函数参数都是以实际实参的副本为初值,而调用段所获得的...

    php 出现Strict Standards: Only variables should be passed by reference in的解决方法

    总结来说,解决“Strict Standards: Only variables should be passed by reference”警告的根本方法是修改代码中的引用传递部分,确保不再使用被废弃的引用传递方式。通过遵循PHP的最佳实践和严格的编码标准,可以...

    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 ...

    CUDA Reference from NVIDIA official site.

    ### CUDA Reference Manual Key Points #### 1. Runtime API Reference The CUDA Runtime API is a core component of the CUDA platform and provides a set of functions for managing GPU resources, executing...

    程序设计语言原理模拟试卷与答案

    2. **引用传递(Passed by Reference):** 在这种情况下,实参的地址被传递给函数,因此对形参的任何修改都会影响到实参。 - **第一次调用:** `swap(value, list[0]);` `value` 和 `list[0]` 的地址被传递,`value` ...

    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;...

    数位板压力测试

    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...

    3 Multiple-Choice Quiz 2.doc

    正确答案是 (a) It is call-by-value。C++ 中的函数参数传递默认是按值传递的。 问题 5 中,讨论了引用变量作为函数参数。正确答案是 (c) It allows a function to modify the original object passed in as the ...

    AVEVA PML快速入门引导

    PML 函数参数都是传引用的(passed-by-reference)而不是传值(passed-by-value)的方式,所以可以通过函数参数返回改变的值。 学习 AVEVA PML 需要掌握基本的编程概念,例如变量、函数、对象等。同时,学习 AVEVA ...

    delphi编译错误.txt

    37. **Constant object cannot be passed as var parameter** - **含义**: 无法将常量对象作为变参传递。 - **解决办法**: 使用可变对象或调整参数类型。 38. **Constant or type identifier expected** - **...

    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, ...

    ecshop基于php5.0版本以上的配置修改

    Strict Standards: Only variables should be passed by reference in D:\wamp\ecshop\includes\cls_template.php on line 406 ``` **解决方法**: ```php $tag_arr = explode(' ', $tag); $tag_sel = array_shift...

    Secrets of the JavaScript Ninja, 2nd Edition

    `const` creates a read-only reference to a value, preventing reassignment but allowing mutation: ```javascript const ninja = { name: "Yoshi" }; ninja.name = "Hanzo"; // Allowed ninja = { name: "Hanzo...

    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...

    Cours-VB-NET-2010-Developpez-com

    - Parameter passing: Parameters can be passed by value or by reference. ##### 10. English to French Lexicon A lexicon providing translations of common programming terms from English to French, which ...

    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 ...

Global site tag (gtag.js) - Google Analytics