Roki20121
Roki20121

Reputation: 115

Swap two booleans in array

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?

Upvotes: 1

Views: 1025

Answers (4)

Jean Logeart
Jean Logeart

Reputation: 53839

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]);

Upvotes: 0

rzysia
rzysia

Reputation: 737

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;
}

Upvotes: 0

No Idea For Name
No Idea For Name

Reputation: 11597

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.

Upvotes: 3

StanislavL
StanislavL

Reputation: 57421

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;
}

Upvotes: 0

Related Questions