Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to code re-factor swapping integers

Tags:

java

swap

We have this code in many places where we swap integers if one value is higher than the other. Is there a way to re-factor this code, so it can be re-used?

    int numerator2 = <some random number>;
    int denominator2 = <some random number>;

    if (numerator2 > denominator2) {
        int temp = denominator2;
        denominator2 = numerator2;
        numerator2 = temp;
    }
like image 429
user339108 Avatar asked Dec 16 '10 04:12

user339108


2 Answers

What your question boils down to is that you want a neat and reusable way to swap swap the values of a pair of bare variables. (I know you want to do this conditionally, but it is easier to explain for the unconditional case.)

Unfortunately, there is no way to do this in Java. The various programming language mechanisms that hypothetically could be used to do this are not available in Java. Here's a summary:

  • In some languages, you would do this using call by reference (e.g. FORTRAN) or INOUT parameter passing (e.g. ObjectiveC):

    int a = 1;
    int b = 2;
    swap(a, b);
    
  • In some languages you can simulate call by reference by passing addresses (e.g. C and C++):

    int a = 1;
    int b = 2;
    swap(&a, &b);
    
  • In some languages, there is a tuple assignment statement (e.g. Perl):

    int a = 1;
    int b = 2;
    a, b = {b, a};
    // or ...
    a, b = swap(b, a); // where swap returns an explicit or implicit tuple.
    
  • In some languages, procedures / methods can return multiple results and there is a special syntax to assign individual results to a different variable (e.g. Mesa ... and I'm sure there are less obscure examples):

    int a = 1;
    int b = 2;
    a, b = swap(b, a);
    

Unfortunately, none of these mechanisms are available in Java. The best you can do is use some kind of mutable wrapper class instead of bare primitive types; e.g.

   IntHolder a = new IntHolder(1);
   IntHolder b = new IntHolder(2);
   swap(a, b);

FOLLOWUP

One could use existing types like AtomicType or Apache Commons' MutableInteger as the wrapper class. I'd recommend the latter since it is marginally faster. Besides, using AtomicType instances doesn't mean you can implement the swap method atomically.

like image 99
Stephen C Avatar answered Nov 09 '22 15:11

Stephen C


Create a class containing the two numbers as member variables. It can accept these in the constructor.

Then create a method on that class that returns a new instance of the same class with the members swapped if they need to be.

like image 21
WW. Avatar answered Nov 09 '22 17:11

WW.