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)./** * Swaps the two given {@code NaturalNumber}s. * * @param n1 * the first {@code NaturalNumber} * @param n2 * the second {@code NaturalNumber} * @updates n1 * @updates n2 * @ensures n1 = #n2 and n2 = #n1 */ private static void swapNN(NaturalNumber n1, NaturalNumber n2) {...}
- 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./** * Squares a given {@code NaturalNumber}. * * @param n * the number to square * @updates n * @ensures n = #n * #n */ private static void square(NaturalNumber n) {...}
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.