EN
Java - compare arrays
5 points
In this short article, we would like to show how to compare 2 arrays in Java.
Note: as arrays comparision we understand comparision on array items.
Quick solution:
xxxxxxxxxx
1
// import java.util.Arrays;
2
3
String[] a = {"1", "2", "3"};
4
String[] b = {"1", "2", "3"};
5
6
System.out.println(Arrays.equals(a, b)); // true
In this section, we can see items comparions example.
xxxxxxxxxx
1
import java.util.Arrays;
2
3
public class HelloWorld{
4
5
public static void main(String []args){
6
7
String[] a = {"1", "2", "3"};
8
String[] b = {"1", "2", "3"};
9
10
System.out.println(Arrays.equals(a, b)); // true
11
}
12
}
Output:
xxxxxxxxxx
1
true
The example presented in this section is useful when we want to check if 2 variables indicate same array.
xxxxxxxxxx
1
import java.util.Arrays;
2
3
public class HelloWorld{
4
5
public static void main(String []args){
6
7
String[] a = {"1", "2", "3"};
8
String[] b = {"1", "2", "3"};
9
10
System.out.println(a == b); // false
11
System.out.println(a == a); // true
12
System.out.println(b == b); // true
13
}
14
}
Output:
xxxxxxxxxx
1
false
2
true
3
true