Skip to Content

Compare Two Java double Arrays Example

  1. /*
  2.   Compare Two Java double Arrays Example
  3.   This java example shows how to compare two double arrays for equality using
  4.   Arrays.equals method.
  5. */
  6.  
  7. import java.util.Arrays;
  8.  
  9. public class CompareDoubleArraysExample {
  10.  
  11.   public static void main(String[] args) {
  12.     //create double arrays
  13.     double[] dblArray1 = new double[]{10.3221,789.23,427.213};
  14.     double[] dblArray2 = new double[]{10.3221,789.23,427.213};
  15.    
  16.     /*
  17.       To compare two double arrays use,
  18.       static boolean equals(double array1[], double array2[]) method of Arrays class.
  19.      
  20.       It returns true if both arrays are equal. Arrays are considered as equal
  21.       if they contain same elements in same order.
  22.      
  23.       Two double elements are considered as equal if
  24.       new Double(d1).equals(new Double(d2))
  25.     */
  26.    
  27.     boolean blnResult = Arrays.equals(dblArray1,dblArray2);
  28.     System.out.println("Are two double arrays equal ? : " + blnResult);
  29.    
  30.     /*
  31.       Please note that two double array references pointing to null are
  32.       considered as equal.
  33.       Also, two NaN values are considerd equal. But 0.0d and -0.0d are
  34.       considered as unequal.
  35.     */
  36.    
  37.   }
  38. }
  39.  
  40. /*
  41. Output of the program would be
  42. Are two double arrays equal ? : true
  43. */