gpt4 book ai didi

Java中检查两个数组是否相等

转载 作者:知者 更新时间:2024-03-12 12:34:13 24 4
gpt4 key购买 nike

在这篇文章中,我们将写一个Java程序来检查两个数组的相等关系。

在这篇文章中,我们将看到三种编写逻辑的方法来检查两个数组的相等关系。

  • 使用一个迭代方法
  • 使用Arrays.equals(array1, array2)方法
  • 写出相等的通用方法

使用一个迭代方法

public class CheckTwoArraysAreEqual {

 public static void main(final String[] args) {

  final int[] array1 = { 1, 2, 3, 4, 5 };
  final int[] array2 = { 1, 2, 3, 4, 5 };

  final boolean intCheck = equals(array1, array2);
  System.out.println("Two Integers are Equal :: " + intCheck);
 }

 public static boolean equals(final int[] a, final int[] a2) {
  if (a == a2)
   return true;
  if (a == null || a2 == null)
   return false;

  final int length = a.length;
  if (a2.length != length)
   return false;

  for (int i = 0; i < length; i++)
   if (a[i] != a2[i])
    return false;

  return true;
 }
}

输出。

Two Integers are Equal :: true

使用Arrays.equals(array1, array2) 方法

import java.util.Arrays;

public class CheckTwoArraysAreEqual {

 public static void main(final String[] args) {

  final int[] array1 = { 1, 2, 3, 4, 5 };
  final int[] array2 = { 1, 2, 3, 4, 5 };

  final boolean intCheck = Arrays.equals(array1, array2);
  System.out.println("Two Integers are Equal :: " + intCheck);
 }
}

输出。

Two Integers are Equal :: true

编写equals通用方法

public class CheckTwoArraysAreEqual {

 public static void main(final String[] args) {

  final String[] s1 =  { "Apple", "banana", "pinapale" };

  final String[] s2 =  { "Apple", "banana", "pinapale" };
  
  final Integer[] array1 = { 1, 2, 3, 4, 5 };
  final Integer[] array2 = { 1, 2, 3, 4, 5 };

  final boolean strCheck = equals(s1, s2);
  System.out.println("Two Strings are Equal :: " + strCheck);
  final boolean intCheck = equals(array1, array2);
  System.out.println("Two Integers are Equal :: " + intCheck);
 }

 public static boolean equals(final Object[] a, final Object[] a2) {
  if (a == a2)
   return true;
  if (a == null || a2 == null)
   return false;

  final int length = a.length;
  if (a2.length != length)
   return false;

  for (int i = 0; i < length; i++) {
   final Object o1 = a[i];
   final Object o2 = a2[i];
   if (!(o1 == null ? o2 == null : o1.equals(o2)))
    return false;
  }

  return true;
 }
}

输出

Two Strings are Equal :: true
Two Integers are Equal :: true

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com