Bryce <> scribbled the following:
> On 22 Jun 2004 04:55:44 -0700, (Bill Reyn)
> wrote:
>>I know we have been over this before, but I still don't get it./*
>>How can you swap two integers in Java? - in C++ I can swap references
>>with 3 lines of code - but how on earth am I supposed to do it in
>>Java, the code below works, but cannot be the right way of doing it.
>>Why not?
> Why on earth would you do it that way...
>>--------------------------------------------------------------------
>>/* this swaps 2 integers correctly, BUT its seems non-OO */
>>class Swap4
>>{
>> static int x=5, y=7 ; // this looks horrid!
> Well, you declared them static. I see no reason why.
> In Java, you don't have pointers. You have references.
> So in short, you cannot swap variables in a method. You would need to
> do it inline like this:
> public class SwapTest {
> public static void main (String[] args) {
> Integer x = new Integer(5);
> Integer y = new Integer(7);
> System.out.println("Before Swap");
> System.out.println(" x=[" + x + "]");
> System.out.println(" y=[" + y + "]");
>
> Integer tmp = x;
> x = y;
> y = tmp;
>
> System.out.println("After Swap");
> System.out.println(" x=[" + x + "]");
> System.out.println(" y=[" + y + "]");
> }
> }
Your example above would work just as well if you used:
int x = 5;
int y = 7;
int tmp = x;
x = y;
y = tmp,
If all your variables are local to one method, it doesn't matter whether
they are primitives or references, you can use their values any way you
like.
The problem, which you don't seem to have grasped, comes when these
variables are passed onto other methods.
In C you can do this:
void swap(int *x, int *y) {
int tmp = *x;
*x = *y;
*y = tmp;
}
In Java, you can't. Not with primitive types, anyway. But if you have
some sort of wrapper object, you can do this:
void swap(IntWrapper x, IntWrapper y) {
int tmp = x.getValue();
x.setValue(y.getValue());
y.setValue(tmp);
}
You can't do this with java.lang.Integer as it doesn't have methods to
change its value, but you can write your own wrapper class.
> More information on the differences between C++ and Java and how Java
> passes values to functions:
> http://www-106.ibm.com/developerwork...y/j-passbyval/
I suggest you read that yourself...
--
/-- Joona Palaste () ------------- Finland --------\
\--
http://www.helsinki.fi/~palaste --------------------- rules! --------/
"All that flower power is no match for my glower power!"
- Montgomery Burns