在 Java 中檢查兩個浮點陣列是否相等


要檢查兩個浮點陣列是否相等,請使用 Arrays.equals() 方法。

在我們的示例中,我們有以下兩個浮點陣列。

float[] floatVal1 = new float[] { 3.2f, 5.5f, 5.3f };
float[] floatVal2 = new float[] { 3.2f, 5.5f, 5.3f };

現在讓我們比較它們是否相等。

if (Arrays.equals(floatVal1, floatVal2)) {
System.out.println("Both are equal!");
}

以下是一個示例,在其中我們比較陣列,同時使用 == 來檢查其他條件。

示例

 線上演示

import java.util.Arrays;
public class Demo {
   public static void main(String args[]) {
      float[] floatVal1 = new float[] { 3.2f, 5.5f, 5.3f };
      float[] floatVal2 = new float[] { 3.2f, 5.5f, 5.3f };
      if (floatVal1 == null) {
         System.out.println("First array is null!");
      }
      if (floatVal2 == null) {
         System.out.println("Second array is null!");
      }
      if (floatVal1.length != floatVal2.length) {
         System.out.println("Both does not have equal number of elements!");
      }
      if (Arrays.equals(floatVal1, floatVal2)) {
         System.out.println("Both are equal!");
      }
   }
}

輸出

Both are equal!

更新日期:2020 年 6 月 26 日

136 次瀏覽

啟動你的職業生涯

透過完成該課程取得認證

開始
廣告