For primitive type: Arrays.equals(a1,a2)
For reference type: Arrays.deepEquals(a1,a2)
How to compare array contents?
A simple way is to run a loop and compare elements one by one.
Java provides a direct method Arrays.equals() to
compare two arrays.
Actually, there is a list of equals() methods in Arrays class
for different primitive types (int, char, ..etc) and one for Object type (which
is base of all classes in Java).
import java.util.Arrays;
class ArraysCompare {
public static void main (String[] args) {
int arr1[] = {1, 2,
3};
int arr2[] = {1, 2,
3};
if (Arrays.equals(arr1, arr2)) {
System.out.println("Same");
} else {
System.out.println("Not same");
}
}
}
Output:
Same
Issue with the equals() method:
import java.util.Arrays;
class ArraysCompare {
public static void main (String[] args) {
// inarr1 and inarr2 have same values
int inarr1[] = {1, 2,
3};
int inarr2[] = {1, 2,
3};
Object[] arr1 = {inarr1}; //arr1 contains only one element
Object[] arr2 = {inarr2}; //arr2 also contains only one element
if (Arrays.equals(arr1, arr2)) { //will not work for reference.
System.out.println("Same");
} else {
System.out.println("Not same");
}
}
}
Output:
Not Same
If the arrays contain arrays inside them or some other
references which refer to different object but have same values.
import java.util.Arrays;
class ArraysCompare {
public static void main (String[] args) {
// inarr1 and inarr2 have same values
int inarr1[] = {1, 2,
3};
int inarr2[] = {1, 2,
3};
Object[] arr1 = {inarr1};//arr1 contains only one element
Object[] arr2 = {inarr2};//arr2 also contains only one element
if (Arrays.deepEquals(arr1, arr2)) {
System.out.println("Same");
} else {
System.out.println("Not same");
}
}
}
Output:
Same
Precise and crisp explanation. Thanks
ReplyDeleteWhat will be the output for
ReplyDeleteimport java.util.Arrays;
class Test
{
public static void main (String[] args)
{
int inarr1[] = {1, 2, 3};
int inarr2[] = {1, 2, 3};
Object[] arr1 = {inarr1}; // arr1 contains only one element
Object[] arr2 = {inarr2}; // arr2 also contains only one element
Object[] outarr1 = {arr1}; // outarr1 contains only one element
Object[] outarr2 = {arr2}; // outarr2 also contains only one element
if (Arrays.deepEquals(outarr1, outarr2))
System.out.println("Same");
else
System.out.println("Not same");
}
}