1

I want to swap two values in an array but i am unable to to it. I am creating a new swap function. I know the value can only be swapped through referencing, but i don't know how to do it. Can someone please help me. Below is the code i am trying to write. I want to swap the array data in class A.

public class test { 
public static void swap(int num[],int num2,int num3) {
   //swap code
    }
public static void main(String...args) {
    A a = new A();
    A obj1 = new A();
    A obj2 = new A();
    swap(a.num,obj1.num[0],obj2.num[2]);
}}
   class A{
        int num[]={1,2,3};
     }
Adi
  • 21
  • 3

2 Answers2

3

int[] arr - arr is reference to the array object. Therefore you can write swap method given this reference to swap required values.

public static void swap(int[] arr, int i, int j) {
    int tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
1

By the way it can be done without temporary variable:

public static void swap(int[] arr, int i, int j) {
    arr[i] ^= arr[j];
    arr[j] ^= arr[i];
    arr[i] ^= arr[j];
}
Ruslan
  • 6,090
  • 1
  • 21
  • 36