How to check the equality of two arrays in Java? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

How to check the equality of two arrays in Java?

Please Help!!!

24th Nov 2016, 4:29 PM
Jaydeep Khatri
Jaydeep Khatri - avatar
5 Answers
+ 5
import java.util.Arrays; public class Main { public static void main(String[] args) throws Exception { int[] ary = {1,2,3,4,5,6}; int[] ary1 = {1,2,3,4,5,6}; int[] ary2 = {1,2,3,4}; System.out.println("Is array 1 equal to array 2?? " +Arrays.equals(ary, ary1)); System.out.println("Is array 1 equal to array 3?? " +Arrays.equals(ary, ary2)); } }
23rd Nov 2016, 5:23 PM
Jaydeep Khatri
Jaydeep Khatri - avatar
+ 4
use the method equals in the Arrays class for example: int [ ] arr1 = {1, 2, 3}; int [ ] arr2 = {1, 2}; if (Arrays.equals (arr1, arr2)) { System.out.println("true"); } else { System.out.println("false"); } the Arrays.equals method will return true if the 2 arrays passed in the parameters are the same, false if not In this case it will return false, so the else statement will be executed (it will print false to the screen)
10th Nov 2016, 10:22 AM
Anitei Leonard
Anitei Leonard - avatar
+ 3
by equality you mean same elements and the same order of elements or just same elememts with no consideration to their order?
10th Nov 2016, 10:15 AM
Burey
Burey - avatar
+ 3
The best way to do that: Arrays.equals(array1, array2); make sure that you sort both arrays at first: Arrays.sort(array);
10th Nov 2016, 7:04 PM
FreakManMega
+ 1
check element by element using Loop, set flag=1 if any element is mismatched.
10th Nov 2016, 12:10 PM
P Sandesh Baliga
P Sandesh Baliga - avatar