java swap的作用,java中的swap()?

hi every body!

I''m beginner in Java.

I have to write a method to exchange value of 2 integer number, that is://......

public void swap(int a, int b){

int temp = a;

a = b;

b = temp;

}

//...

It doesn''t work, certainly! But I don''t know the way to correct it. Please!

Thanks so much!

解决方案

The reason why it doesn''t work is that it doesn''t swap the values of the integers you pass to the method. The method only swap the values of the two variables (a and b) that are declared in the method - it doesn''t affect any variables outside of the method, even if they are passed as arguments to this method.

I did some Googling, and it seems it isn''t that easy creating a swap method in Java, but I found the following site, which I hope you''ll find useful.

Swapping in C, C++, and Java[^]

Sorry, but you cannot do that in Java. The only way to achieve what you want is to create a class that contains two integers and has a swap method to exchange them. Then all references to your integers would be through an instance of your class. Try rereading your Java documentation and thinking in terms of objects rather than primitive data types.

In java, every object is passed as reference to methods except primitive types like int, byte, Integer, Byte.(Sub. ed. Integer and Byte are also primitive type)

You could try to change the function to ''swap(int[] arr,int index1, index2)'' and swap elements at specified indexes or you could pass objects to the method like swap(ObjectName a,ObjectName b) and swap objects'' field values by something like :

Integer tmp = a.value;

a.value = b.value;

b.value = tmp;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值