如何在没有java utils的情况下比较两个字符串数组

2022-01-25 00:00:00 arrays compare java

检查数组arr1是否包含与java中相同顺序的arr2相同的元素.

Check to see if the array arr1 contain the same elements as arr2 in the same order in java.

例如:

    isTheSame({"1", "2", "3"}, {"1", "2", "3"}) → true
    isTheSame({"1", "2", "3"}, {"2", "1", "1"}) → false
    isTheSame({"1", "2", "3"}, {"3", "1", "2"}) → false

目前为止

public boolean isTheSame(String[] arr1, String[] arr2)
{
   if (arr1.length == arr2.length)
   {
      for (int i = 0; i < arr1.length; i++)
       {
          if (arr1[i] == arr2[i])
          {
            return true;
          }
       }
    }
    return false;  
 }

这样做的问题是它只比较两个数组的第一个元素.

The problem with this is that it only compares the first element of the two arrays.

推荐答案

您一直在迭代,直到找到匹配项.你应该寻找一个不匹配的字符串,你应该使用 equals 而不是 ==

You are iterating until you find a match. You should instead be looking for a String which doesn't match and you should be using equals not ==

// same as Arrays.equals()
public boolean isTheSame(String[] arr1, String[] arr2) {
    if (arr1.length != arr2.length) return false;
    for (int i = 0; i < arr1.length; i++)
        if (!arr1[i].equals(arr2[i]))
            return false;
    return true;
}

仅供参考,这就是 Arrays.equals 在处理 null 值时所做的事情.

FYI This is what Arrays.equals does as it handle null values as well.

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

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

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

    return true;
}

相关文章