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
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 };
if (array1.length != array2.length)
System.out.println( "Arrays are not Equal" );
else {
for ( int i = 0 ; i < array1.length; i++)
{
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
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 };
if (Arrays.equals(array1, array2))
System.out.println( "Arrays are Equal" );
else
System.out.println( "Arrays are Not Equal" );
}
}
|
Time Complexity: O(1)
Last Updated :
28 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...