在这篇文章中,我们将写一个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
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
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
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2018/08/java-program-to-check-equality-of-two-arrays.html
内容来源于网络,如有侵权,请联系作者删除!