Java Program to Compare two Double Arrays
Java double array is used to store double data type values only. The default value of the elements in a double array is 0.
We can compare two double arrays by two ways:
- By naive approach of traversing through the whole array and comparing each element.
- By Arrays.equals() method.
Method 1: Naive Approach
- By Comparing one element at a time by traversing through both the arrays using for loop.
Java
// Java program to compare two double arrays import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws java.lang.Exception { // Two double arrays array1 and array2 double [] array1 = { 1.5 , 2.5 , 3.5 , 4.5 }; double [] array2 = { 1.5 , 2.5 , 3.5 }; // when the length of two arrays are not // same, then both the arrays cannot be equal // so no need of comparing each element if (array1.length != array2.length) System.out.println( "Arrays are not Equal" ); else { for ( int i = 0 ; i < array1.length; i++) { // comparing each and every element if (array1[i] != array2[i]) { System.out.println( "Arrays are not Equal" ); System.exit( 0 ); } } System.out.println( "Arrays are Equal" ); } } } |
Output
Arrays are not Equal
Time Complexity: O(n)
Method 2: Using Arrays.equals() method
Syntax :
public static boolean equals(int[] a, int[] a2)
Parameters :
- a1 – one array to be tested for equality
- a2 – the other array to be tested for equality
Returns : true if the two arrays are equal
Java
// Java program to compare two double arrays import java.util.*; import java.lang.*; import java.io.*; class GFG { public static void main(String[] args) throws java.lang.Exception { double [] array1 = { 1.5 , 2.5 , 3.5 , 4.5 }; double [] array2 = { 1.5 , 2.5 , 3.5 , 4.5 }; // Arrays.equals() compares the equality // of two arrays if (Arrays.equals(array1, array2)) System.out.println( "Arrays are Equal" ); else System.out.println( "Arrays are Not Equal" ); } } |
Output
Arrays are Equal
Time Complexity: O(1)