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.

  1. Given this contract for the method swapNN:
    Implement the swapNN method using copyFrom (and not transferFrom).

  2. 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).

  3. (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

  1. 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.
  2. 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.