Program to demonstrate how to compare two or more arrays equality in Java
package com.hubberspot.collections.example; import java.util.Arrays; public class CompareArraysEquality { public static void main(String[] args) { // 1. Lets create three arrays of same size String[] array1 = new String[5]; String[] array2 = new String[5]; String[] array3 = new String[5]; // 2. Lets add few strings to each of them array1[0] = "One"; array1[1] = "Two"; array1[2] = "Three"; array1[3] = "Four"; array1[4] = "Five"; array2[0] = "A"; array2[1] = "New"; array2[2] = "Different"; array2[3] = "Array"; array2[4] = "Created"; array3[0] = "One"; array3[1] = "Two"; array3[2] = "Three"; array3[3] = "Four"; array3[4] = "Five"; // 3. Using Arrays.equals() to compare whether // arrays are equal or not boolean firstCompare = Arrays.equals(array1, array2); boolean secondCompare = Arrays.equals(array1, array3); boolean thirdCompare = Arrays.equals(array2, array3); // 4. printing the result on the console System.out.println("array1 equals array2 : " + firstCompare); System.out.println("array1 equals array3 : " + secondCompare); System.out.println("array2 equals array3 : " + thirdCompare); } }
Output of the program :