如何在没有java utils的情况下比较两个字符串数组 [英] how to compare two string arrays without java utils

查看:18
本文介绍了如何在没有java utils的情况下比较两个字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查数组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;
}

这篇关于如何在没有java utils的情况下比较两个字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆