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:/** * 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) {...}Implement the
swapNNmethod usingcopyFrom(and nottransferFrom). -
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 theswapNNmethod usingtransferFrom. Assuming,n1andn2in the contract above are of the same implementation, implement theswapNNmethod usingtransferFrom(and notcopyFrom). -
(This question is not related to swapping, but it is a good one nonetheless.) Using any of the methods of the
NaturalNumbercomponent family, implement the method specified as follows:/** * Squares a given {@code NaturalNumber}. * * @param n * the number to square * @updates n * @ensures n = #n * #n */ private static void square(NaturalNumber n) {...}Be careful when handling references.
Additional Questions
- Is there any alternative way to implement a
swapmethod 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
swapmethod that swaps two arguments of an immutable reference type (say,StringorXMLTree)? Either provide an implementation or an argument of why it is not possible.