how to compare two string arrays without java utils

心不动则不痛 提交于 2019-12-01 00:03:17

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;
}

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;
}
public boolean isTheSame(String[] arr1, String[] arr2)
{
    if (arr1.length == arr2.length)
    {
         for (int i = 0; i < arr1.length; i++)
          {
             if ((arr1[i] != null && arr2[i] != null && !arr1[i].equals(arr2[i]))
                 || (arr1[i] != null && arr2[i] == null) || 
                 (arr2[i] != null && arr1[i] == null))
              {
                return false;
              }
          }
    } else {
         return false;  
    }
    return true;  
 }

But it is very unoptimal.

Yes, it will only compare the first element. Look what it is doing:

public boolean isTheSame(String[] arr1, String[] arr2)
{
    if (arr1.length == arr2.length)
    {
         for (int i = 0; i < arr1.length; i++)
          {
             // if the elements are equal ..
             // (NOTE: this will only be true for INTERNED strings!!)
             if (arr1[i] == arr2[i]) // fixed typo
              {
                // .. then STOP LOOKING and RETURN TRUE
                // wait- WHY?
                return true;
              }
          }
          // searched everything- but still RETURN FALSE??
    }
    return false;  
 }

While the usage of == is not the problem with the provided example data due to string interning, it will bite you someday for real data. Don't use == for objects unless identity equality is desired.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!