java 函数中交换对象,在Java中交换两个字符串,方法是将它们传递给实用程序函数,但不返回对象或使用包装类...

I am trying to swap two strings in Java. I never really understood "strings are immutable". I understand it in theory, but I never came across it in practice.

Also, since String is an object in Java and not a primitive type, I don't understand why the following code prints the same result twice, instead of interchanging the words!

public static void main(String[] args)

{

String s1 = "Hello";

String s2 = "World";

System.out.println(s1 + " " + s2);

Swap(s1, s2);

System.out.println(s1 + " " + s2);

}

public static void Swap(String s1, String s2)

{

String temp = s1;

s1 = s2;

s2 = temp;

}

I want it to print

Hello World

World Hello

But it is printing

Hello World

Hello World

I thought s1 and s2 are references and hence the references should be swapped and the new ones should point to the other one respectively. Where am I going wrong?

解决方案

I thought s1 and s2 are references and hence the references should be swapped and the new ones should point to the other one respectively.

Yes. Locally inside swap, this is exactly what happens.

However, s1 and s2 are copies of the references passed into the function, so the effect remains local. Note that it’s not the strings that are copied (since String is a reference type). But the references are copied.

… and since parameter references are always copied in Java, writing a swap function according to your specifications is, quite simply, not possible.

If you have problems understanding the difference, consider this: you want to write a letter to a friend so you copy her postal address from your address book onto an envelope. By this process, you certainly didn’t copy her home (copying a whole house is a bit difficult in practice) – you only copied the address.

Well, an address refers to her home so it’s exactly like a Java reference.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值