1

I have an array of boolean values. Now I need swap item from position1 with item from position2 ;

I use this void

public static void swap(boolean x, boolean z){
   writeln("swapping");
   boolean temp = x;
   x=z;
   z=temp;
}

and

swap(position[a],position[moves[b]);

but it don't work. Just not swap. Any ideas?

No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
Roki20121
  • 105
  • 1
  • 12
  • 1
    params here are passed by value and not by reference – Bhargav Rao Dec 10 '14 at 13:12
  • what doesn't work ? explain... what are the unexpected results you are getting? what are you giving as parameters? – Bart Hofma Dec 10 '14 at 13:13
  • pointers arent used in Java to access variable over function, possible answer is just place global variable **position**. – machei Dec 10 '14 at 13:18
  • possible duplicate of [Is Java "pass-by-reference" or "pass-by-value"?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – Joe Dec 10 '14 at 13:36

4 Answers4

2

yes, you need to do:

public static void swap(boolean[] arr, int x, int z){    
    writeln("swapping");
    boolean temp = arr[x];
    arr[x]=arr[z];
    arr[z]=temp;    
}

because when you send position[a] and position[b] java will copy their value to a new parameter, and so when you leave the swap function, no change was done to the variables

to understand more you can read on pass-by-value and pass-by-ref in java here

When the method or constructor is invoked, the values of the actual argument expressions initialize newly created parameter variables, each of the declared Type, before execution of the body of the method or constructor. The Identifier that appears in the DeclaratorId may be used as a simple name in the body of the method or constructor to refer to the formal parameter.

No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
0

Pass the array and 2 indexes

public static void swap(boolean[] arr, int index1, int index2){
    writeln("swapping");
    boolean temp = arr[index1];
    arr[index1]=arr[index2];
    arr[index2]=temp;
}
StanislavL
  • 56,971
  • 9
  • 68
  • 98
0

You're passing simple types - and u can't change their values. Try

public static void swap(boolean[] arr, int index1, int index2){
    writeln("swapping");
    boolean temp = arr[index1];
    arr[index1]=arr[index2];
    arr[index2]=temp;
}
rzysia
  • 737
  • 1
  • 11
  • 26
0

Since Java only passes by value, you can swap elements in an array doing:

public static void swap(boolean[] a, int index1, int index2) {
    boolean tmp = a[index1];
    a[index1] = a[index2];
    a[index2] = tmp;
}

and you can call it:

swap(position, a, moves[b]);
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118