[ת]Does Java pass by reference or pass by value?
http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
Does Java pass by reference or pass by value?
Why can't you swap in Java?
By Tony
Sintes, JavaWorld.com, 05/26/00
Print
Email
Feedback
Resources
Discuss
(76)
Digg
Reddit
SlashDot
Stumble
del.icio.us
Technorati
dzone
If Java uses the pass-by reference, why
won't a swap function work?
Your question demonstrates a common error made by
Java language newcomers. Indeed, even seasoned veterans find it
difficult
to keep the terms straight.
Java does manipulate objects by reference, and
all object variables are references. However, Java doesn't pass method
arguments
by reference; it passes them by value.
Take the badSwap()
method for
example:
public void badSwap(int var1, int var2)
{
int temp = var1;
var1 = var2;
var2 = temp;
}
When badSwap()
returns, the
variables passed as arguments will still hold their original values. The
method will also fail if we change
the arguments type from int
to Object
,
since Java passes object references by value as well. Now, here is
where it gets tricky:
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);
}
If we execute this main()
method,
we see the following ou
Ïà¹ØÎĵµ£º
ÏÈÀ´Á˽âÒ»ÏÂÁ´±íģʽµÄÔÀí£º
Ê×ÏÈдһ¸öJavaBean£¬ÄÚÈÝÊÇÒªÌí¼ÓµÄÔªËغ͸ÃÔªËصĽڵ㡣
public class NodeBean implements Serializable
{
private Object data; //ÔªËر¾Éí
private NodeBean next; //ÏÂÒ»¸ö½Úµã
&n ......
ÔÌùµØÖ·¸½ÓÚ´Ë£º Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=602711 È«ÎÄÈçÏ£º
javaѧϰ֮µÀ
1.µ½ÍøÉÏ¿´¿´¸ßÊÖ¶ÔJAVAµÄһЩ¿´·¨£¬ÒÔ¼°JavaµÄÇ°¾°¡£
2.дһ¸ö¼òµ¥µÄÈëÃÅÀý×Ó£¬±ÈÈçHelloWorld£¬¿ÉÒÔʹÓÃUltraEditÀ´Ð´£¬ÈÃÄã¶ÔJAVAµÄ±àÒëÔËÐÐÓÐÒ»¸ö¸ÐÐÔµÄÈÏʶ¡£
3.ϵͳµØ·ôdzµØÁ˽âJavaµÄ¸÷¸ö²¿·Ö£¬° ......
½ñÌìÊÇдµÚһƪ´«ÖDz¥¿Í½Ì³ÌÈÕÖ¾£¬Ò²ÊÇÎÒ¿´
JavaScript
ÊÓƵµÄµÚÒ»Ìì¡£
ÏÈ˵ԵÓÉ°É¡£´óÈý»¹ÓÐÈý¸öÔ¾ÍÒª½áÊøÁË£¬¿ÉÎÒ»¹Ã»Óиоõµ½×Ô¼ºÄܹ»ÓÐ×ã¹»µÄÄÜÁ¦ÕÒµ½·ÝºÃ¹¤×÷£¬´óѧÆÚ¼äѧµ½µÄ¶¼ÊÇЩƤëºÍÀíÂÛ£¬ÎÒ²»Ïëµ½ÁËÕÒ¹¤×÷µÄʱºò£¬ÃæÊÔ¹ÙÎÊÎÒ»á
XXX
Âð£¿ÎÒ˵²»»á¡£Òò´ËÎÒÏëͨ¹ýÅàѵÔö¼Ó×Ô¼ºµÄ¾ºÕùÁ¦¡£ÎÒ±¨Á˱¾µØµÄÒ»¼Ò
I ......
0. ѧϰһÕÂÕÆÎÕÒ»ÕÅ£¬È»ºóÔÙ²»¶ÏµÄÓá£
1£® ÕÒһЩ±È½Ï¾µäµÄÀý×Ó£¬Ô´Âë(Ô´Âë°®ºÃÕß)£¬ ÿ¸öÀý×ӱȽϼ¯ÖÐÒ»ÖÖ±à³Ì˼Ïë¶øÉè¼ÆµÄ£¬±ÈÈçÔÚÎÒµÄʵ¼ùµ±ÖУ¬ÎÒÔø¾Ñ§Ï°¹ýÒ»¸öºÜ¾ µäµÄÀý×Ó¾ÍÊÇÓÃJavaʵÏÖµÄHotDraw£¨Ô´×ÔSmallTalk£©£¬Äã¿ÉÒÔÓÃrolemodel»òhotdrawÔÚ ËÑË÷ÒýÇæÉÏÕÒһϣ¬ÎҼDz»´óÇå ......