天天看點

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

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;