Understanding Java Arrays -
please @ following code :
public static void main(string[] args) { random random = new random(); int[] array = new int[10]; arrays.setall(array, operand -> random.nextint(10)); system.out.println(arrays.tostring(array)); swap(array, 0, 9); system.out.println(arrays.tostring(array)); } static void swap(int[] array, int i, int j) { int temp = array[i]; // pass value ?? array[i] = array[j]; // value of temp doesn't change, why? array[j] = temp; // temp == array[i] }
what happens in method swap
?
i need full explanation , low level.
edit :
ok, let me show example :
public class stringholder { private string value; public stringholder(string value) { this.value = value; } public string getvalue() { return value; } public void setvalue(string value) { this.value = value; } @override public string tostring() { return getvalue(); } }
main method :
public static void main(string[] args) { stringholder[] holders = new stringholder[]{new stringholder("string 1")}; stringholder tmp = holders[0]; holders[0].setvalue("string 2"); system.out.println(tmp); system.out.println(holders[0]); }
output :
string 2 string 2
according @chokdee's answer, tmp
new variable , have it's own piece of memory...
but when apply changes original variable (holder[0]
), affects tmp
.
another example :
public static void main(string[] args) { stringholder[] holders = new stringholder[]{new stringholder("string 1")}; stringholder tmp = holders[0]; holders[0] = new stringholder("string 2"); system.out.println(tmp); system.out.println(holders[0]); }
output :
string 1 string 2
thanks in advance.
i'll answer edit question.
public static void main(string[] args) { stringholder[] holders = new stringholder[]{new stringholder("string 1")}; stringholder tmp = holders[0]; holders[0].setvalue("string 2"); system.out.println(tmp); // string 2 system.out.println(holders[0]); // string 2 }
because both holding reference same object.
public static void main(string[] args) { stringholder[] holders = new stringholder[]{new stringholder("string 1")}; stringholder tmp = holders[0]; holders[0] = new stringholder("string 2"); system.out.println(tmp); // string 1 system.out.println(holders[0]); // string 2 }
in case reference hold tmp. after assign new stringholder
object holders[0]
reference in tmp turned actual object. normally, if did not have tmp
garbage collector remove object. in end have two different stringholder
objects.
Comments
Post a Comment