English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

3 answers

run4ever79 was partly correct. The method receiving int parameters receives the actual values (put on the stack), not references to an object. Using Integer objects doesn't quite work since they have no mutator method to change the stored value.

The trick would be to know corresponding instance variables or class (static) variables for which the values are to be swapped.

If a general purpose method is needed, then the arguments should be of a mutable type. A simple solution is to use single element int arrays as parameters.

void swap(int[] a, int[] b){
int temp = a[0];
a[0] = b[0];
b[0] = temp;
}

Why you would need such a method is beyond me, though. For example, if I wanted to swap width and height for a gui component, why do this:

int x = c.getWidth();
int y = c.getHeight();
int[] a = {x};
int[]b = {y};
swap(a, b);
setSize(a[0], b[0]);

when you could just do this:
int x = c.getWidth();
int y = c.getHeight();
setSize(y,x);

2006-10-24 07:19:06 · answer #1 · answered by vincentgl 5 · 0 0

It's going to be something like this:

int temp;
int integer1 = 10;
int integer2 = 20;

temp = integer1;
integer1 = integer2;
integer2 = temp;


You'd use a void function because you don't have to return anything.

If this isn't what you're looking for, clarify a bit and I'll check back in the next couple of minutes to see if I can help...

2006-10-23 17:18:48 · answer #2 · answered by Anonymous · 0 0

The previous answer is very close, you need to use a java.lang.Integer as the parameters to your function since the primative 'int' type will use pass by value semantics instead of the pass-by-reference semantics that you want for this kind of swap function.

2006-10-23 19:18:02 · answer #3 · answered by run4ever79 3 · 0 0

fedest.com, questions and answers