Homework: Swapping
As you have seen in the last homework and lab, it is impossible
to implement a swap method that swaps two arguments of any
type by using the common solution involving three assignments. But
for NaturalNumber it is possible to implement swap
by employing either NaturalNumber's
copyFrom or Standard's
transferFrom.
- Given this contract for the method swapNN:
Implement the swapNN method using copyFrom (and
not transferFrom).
- If we are willing to require that the two NaturalNumbers are
of the same implementation, then it is possible to provide a faster
implementation for the swapNN method using transferFrom.
Assuming, n1 and n2 in the contract above are of the
same implementation, implement the swapNN method using
transferFrom (and not copyFrom).
- (This question is not related to swapping, but it is a good
one nonetheless.) Using any of the methods of the NaturalNumber
component family, implement the method specified as follows:
Be careful
when handling references.
Additional Questions
- Is there any alternative way to implement a swap
method that swaps two arguments of a primitive type (say, int)?
Either provide an implementation or an argument of why it is not
possible.
- Is there any alternative way to implement a swap
method that swaps two arguments of an immutable reference type
(say, String or XMLTree)? Either provide an
implementation or an argument of why it is not possible.