Swapping Values

Suppose we have a need to swap the values of two variables that are of the same type a large number of times. A brute force solution would be:

save_var = var_a;
var_a = var_b;
var_b = save_var;

Since we need to perform the swap of variable frequently, we may consider the following:

save_var = var_a.getValue();
var_a.setValue(var_b.getValue());
var_b.setValue(save_var);

This is useful for all classes we write, but is not a solution for built-in classes, like Integer. We can use a wrapper pattern to wrap these classes in our own classes:

public class IntegerVariable
{
Integer value;

public IntegerVariable(Integer _value)
{
this.value = _value;
} // IntegerVariable(Integer)

public void setValue(Integer newvalue)
{
this.value = newvalue;
} // setValue(Integer)

public Integer getValue()
{
return this.value;
} // getValue()

public void swap(IntegerVariable other)
{
Integer tmp = this.value;
this.setValue(other.getValue());
other.setValue(tmp);
} // swap(IntegerVariable other)
} // class IntegerVariable

There is a problem with this solution. The problem is that we have to implement a XXXVariable class for every class XXX.

1. Transform the implementation for class IntegerVariable to a generic class called Variable. Submit all .java files.

2. Provide a 1-2 page design description of your implementation based on the following

  • Overview of your design
  • Design benefits e.g., what are the benefits of this design in comparison to alternative designs
  • Design details brief description of your methods

3. Provide JUnit tests for your implementation.

Academic Honesty!
It is not our intention to break the school's academic policy. Posted solutions are meant to be used as a reference and should not be submitted as is. We are not held liable for any misuse of the solutions. Please see the frequently asked questions page for further questions and inquiries.
Kindly complete the form. Please provide a valid email address and we will get back to you within 24 hours. Payment is through PayPal, Buy me a Coffee or Cryptocurrency. We are a nonprofit organization however we need funds to keep this organization operating and to be able to complete our research and development projects.