Search code examples
javaarraysswapjcreator

How do i Swap Data of an Arrays?


   public class Swap_Numbers {

       public static void main(String[] args) {


              int numTens[] = {1, 2, 3, 4, 5}; // First array of numbers
              int numHundred[] = {100, 200, 300, 400, 500}; //Second Array of Numbers


       System.out.println (numTens[3]); // I want my numTens displays numHundred
       System.out.println (numHundred[4]); // I want my numHundred displays numTens
  }
 }

I just don't know what codes should i use to swap the data of numTens and numHundred without using extra variables.. hope some can explain me how Thanks!


Solution

  • I just don't know what codes should i use to swap the data of numTens and numHundred without using extra variables

    You shouldn't, basically. Just take the simple route of a temporary variable:

    int[] tmp = numTens;
    numTens = numHundred;
    numHundred = tmp;
    

    For ints you can actually swap the values within the arrays using arithmetic without temporary variables (which is not the same as swapping which arrays the variables refer to), but it would be very odd to actually find yourself in a situation where you want to do that. Sample code:

    import java.util.Arrays;
    
    public class Test { 
    
        public static void main(String[] args) {
            int[] x = { 1, 2, 3, 4, 5 };
            int[] y = { 15, 60, 23, 10, 100 };
    
            swapValues(x, y);
            System.out.println("x: " + Arrays.toString(x));
            System.out.println("y: " + Arrays.toString(y));
        }
    
        static void swapValues(int[] a, int[] b) {
            // TODO: Validation
            for (int i = 0; i < a.length; i++) {
                a[i] += b[i];
                b[i] = a[i] - b[i];
                a[i] -= b[i];
            }
        }
    }
    

    Even there, I would actually write swapValues using a temporary variable instead, but the above code is just to prove a point...