Array comparision #37567
Array comparision
#37567
how come arrayNm==arrayGm is true?? I changed the index at 0 in arrayGm to -1 |
Answered by
MaryamZi
Aug 30, 2022
Replies: 1 comment 1 reply
|
With If what's required is to create a copy of the array value, the We can use the exact equality ( import ballerina/io;
public function main() {
int[] a = [2, 3, 4, 5, 4];
int[] b = a;
io:println(a == b); // true
io:println(a === b); // true, since they both refer to the same value
b[0] = -1;
io:println(a == b); // true since `a` and `b` refer to the same value
int[] c = [2, 3, 4, 5, 4];
int[] d = c.clone(); // Assign a copy of the array value referred to by `c`
io:println(c == d); // true since the member values are the same
io:println(c === d); // false now since `d` refers to a clone of the value referred to by `c`
c[0] = 25;
io:println(c == d); // now false since `d` was referring to a clone of the value held by `c`
// and since `c` was updated, the member values in `c` and `d` are now different
} |
1 reply
Answer selected by
navaneeth-algorithm
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With
int[] arrayGm = arrayNm;arrayGmrefers to the same array value referred to byarrayNm. Therefore, any change done to the array value viaarrayGmhappens on the same array value that is assigned toarrayNm. So both variables refer to the same array value, which is why even after the change the equality check will result in true anyway.If what's required is to create a copy of the array value, the
lang.value:clonelanglib function (int[] arrayGm = arrayNm.clone();) can be used.We can use the exact equality (
===) check to check if the variables refer to the same value.