Comparing Arrays
To Compare 2 arrays we use Arrays class equals method.As Objects class 'equals' method and '==' only checks wether the variables refrences are same or not. Equals method checks the elements of the array.
/*
http://www.ProbCOMP.com
To Compare 2 arrays we use Arrays class equals method.As Objects class 'equals' method and '==' only checks wether the variables refrences are same or not. Equals method checks the elements of the array.
*/
import java.util.Arrays;
public class ComparingArray{
public static void main(String args[])
{
int[] originalArray = {1,2,3,4,5};
int[] copyArray = new int[5];
System.arraycopy(originalArray, 0, copyArray, 0, originalArray.length);
// Objects class method only compares refrences and not the values thus the value returned will be false as in case of copy or clone
// the arrays are stored and different locations
System.out.println("\nCompare");
System.out.println("Using Object class equals() method: " + (originalArray.equals(copyArray)));
System.out.println("Using ==: " + (originalArray == copyArray));
System.out.println("Using Arrays class equals() method: " + (Arrays.equals(originalArray, copyArray)));
int[] clonedArray = originalArray.clone();
System.out.println("\nCompare");
System.out.println("Using Object class equals() method: " + (originalArray == clonedArray));
System.out.println("Using ==: " + (originalArray.equals(clonedArray)));
System.out.println("Using Arrays class equals() method: " + (Arrays.equals(originalArray, clonedArray)));
}
}
Download Program


