Java 循环遍历两个数组以检查是否相等

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23166193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:09:03  来源:igfitidea点击:

Looping through two arrays to check if equal

javaarraysequals

提问by leslie

Trying to check if two arrays are equal, meaning same length and same elements in positions.

试图检查两个数组是否相等,这意味着相同的长度和相同的位置元素。

I've tried Arrays.equals(1,2) but it's still coming out as false, while it needs to be coming out as true.

我已经尝试过 Arrays.equals(1,2) 但它仍然显示为假,而它需要显示为真。

I've tried to create a nested for loop to check each index but I am still getting false.

我试图创建一个嵌套的 for 循环来检查每个索引,但我仍然得到错误。

My code:

我的代码:

public boolean equals(double[] s) //for loop checking each element
{
    if (s==null)
    {
        return false;
    }
    for (int i=0;i<data.length;i++)
    {
        for(int j=0;j<s.length;j++)
        {
            if (data[i]!=s[j])
            {
                return false;
            }
        }
    }
    return true;

}

采纳答案by wns349

You don't need a nested loop to check the elements. In fact, your code is wrong in a sense that it's checking all the elements from one array to another.

您不需要嵌套循环来检查元素。事实上,您的代码在某种意义上是错误的,它正在检查从一个数组到另一个数组的所有元素。

You might want to

你可能想要

// Check to make sure arrays have same length
if (data.length != s.length) 
   return false;

for (int i=0;i<data.length;i++)
{
    if (data[i]!=s[i])
    {
       return false;
    }
}
return true;

回答by Butani Vijay

You can use as below :

您可以使用如下:

if(arr1.length!=arr2.length) 
   return false;

for(int index=0;index<arr1.length;index++)
{
    if (arr1[index]!=arr2[index])
         return false;

}
return true;

回答by Bohemian

Don't reinvent the wheel!

不要重新发明轮子!

public boolean equals(double[] s) {
    return Arrays.equals(s, data);
}

Arrays.equals()compares array lengths and each element.

Arrays.equals()比较数组长度和每个元素。

回答by Harry Blargle

if you want to see if they have the same elements but you don't care if they have the same order, sort them first.

如果您想查看它们是否具有相同的元素但不关心它们是否具有相同的顺序,请先对它们进行排序。

Arrays.sort(data);
Arrays.sort(s);
return Arrays.equals(data,s);