|
Re: An easy question,but I don't know
|
Posted: May 10, 2005 6:34 AM
|
|
The original problem seems simple:
What is a simple way to write a method that takes two integers and swaps them?
What we'd like to do is to write code that says something simple like: swap(a,b)
and expect the values to be swapped.
In Java, since primitives are passed by value, you have to say something like: (b,a) = swap(a,b) instead.
In Java, you can only return one value from a method.
Hence, we are left with no alternative but to return an array of two values and expect the client code to resolve the values. I assume that the client code would never be bundled into an array in the first place; that was done merely as an artifact of the method created. Therefore, the other objection that the client code expects to pass this array to some other object will not arise.
As mentioned earlier, Python lets you do it simply by saying: b,a = a,b
Java, the language, makes it very difficult to do simple things and is very verbose, as this example illustrates.
|
|