Java开发网 Java开发网
注册 | 登录 | 帮助 | 搜索 | 排行榜 | 发帖统计  

您没有登录

» Java开发网 » Java SE 综合讨论区 » Java与OOP初步  

按打印兼容模式打印这个话题 打印话题    把这个话题寄给朋友 寄给朋友    该主题的所有更新都将Email到你的邮箱 订阅主题
flat modethreaded modego to previous topicgo to next topicgo to back
作者 Re:请教方法返回多个元素问题 [Re:lou_nj]
Jcat

熊猫的猫



发贴: 266
积分: 16
于 2006-04-05 12:30 user profilesend a private message to usersend email to Jcatsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
1.基本类型作为参数传递时,是传递值的拷贝。(即,无论你怎么改变这个拷贝,原值是不会改变的)
class Test1
{
public static void main(String[] args)
{
int n = 3;
System.out.println("Before change, n = " + n);
changeData(n);
System.out.println("After changeData(n), n = " + n);
}

public static void changeData(int nn)
{
nn = 10;
}
}


2.在Java中对象作为参数传递时,是把对象在内存中的地址拷贝了一份传给了参数。(即,把对象的引用传递过去,如果引用在方法内被改变了,那么原对象也跟着改变)
class Test2
{
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer("Hello ");
System.out.println("Before change, sb = " + sb);
changeData(sb);
System.out.println("After changeData(n), sb = " + sb);
}

public static void changeData(StringBuffer strBuf)
{
strBuf.append("World!");
}
}


3.new操作符操作成功后总会在内存中新开辟一块存储区域。(即,由于sb和strBuf中存放地址不一样了,所以虽然strBuf指向的内存中的值改变了,但sb指向的内存中值并不会变)
class Test3
{
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer("Hello ");
System.out.println("Before change, sb = " + sb);
changeData(sb);
System.out.println("After changeData(n), sb = " + sb);
}

public static void changeData(StringBuffer strBuf)
{
strBuf = new StringBuffer("Hi ");
strBuf.append("World!");
}
}


另外,String类是个特殊的类,对它的一些操作符是重载的,如:
String str = “Hello”;   
等价于
String str = new String(“Hello”);
String str = “Hello”;

str = str + “ world!”;
等价于
str = new String((new StringBuffer(str)).append(“ world!”));

所以,String对象和基本类型一样,一般情况下作为参数传递,在方法内改变了值,而原对象是不会被改变的。

以上内容整理自http://www.javaeasy.com/ArticleShow.asp?ArticleID=172&ArticlePage=1
原文作者:yuanmeng163 出处:CSDN


Jcat edited on 2006-04-05 12:55

编程,游泳,睡觉--SleepingCat

话题树型展开
人气 标题 作者 字数 发贴时间
6211 请教方法返回多个元素问题 lou_nj 403 2006-04-04 16:42
5079 Re:请教方法返回多个元素问题 arroyo 33 2006-04-05 11:19
5750 Re:请教方法返回多个元素问题 Jcat 1863 2006-04-05 12:30

flat modethreaded modego to previous topicgo to next topicgo to back
  已读帖子
  新的帖子
  被删除的帖子
Jump to the top of page

   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923