递归地实现equals方法 [英] Implementing an equals method recursively

查看:60
本文介绍了递归地实现equals方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我需要比较两个数组,并检查它们在相同位置是否具有相同的值(当然是递归的).我当前的代码出现错误:数组超出索引异常:20

Basically, I need to compare two arrays and check if they have the same values in the same positions (recursively of course). I get an error with my current code: Array out of index exception:20

我现在拥有的代码如下:

The code I have right now looks as follows:

    private boolean equalsHelper(int[] first, int[] second, int iStart, int iEnd){
    if (first[iStart] == second[iStart]){
        if (equalsHelper(first,second,(iStart+1),iEnd))
        {
            return true;
        }
    }
    if (iStart == iEnd){
        return first[iEnd] == second[iEnd];
    }
    return false;
}

推荐答案

不考虑递归是否是正确的解决方案的问题(实际上不是,这里的迭代是微不足道的,并且性能会更好),问题在于直到递归调用之后,才检查终止条件( iStart == iEnd ).

Leaving aside the question of whether recursion is the right solution (it really isn't, iteration here is trivial and will perform better), the problem is that the termination condition (iStart == iEnd) is not checked until after the recursive call.

任何递归算法都必须a)检查是否适合继续递归,以及b)在进行此检查后 进行递归调用.不包括第一步或不按顺序执行步骤,将导致无限递归,直到达到错误为止(如果没有其他任何先发生的情况,则为 StackOverflowError ).

Any recursive algorithm must a) check whether it is appropriate to continue recursing, and b) do the recursive call after that check. Failing to include the first step, or doing the steps out of order, will result in infinite recursion until an error is reached (StackOverflowError if nothing else happens first).

在进行递归调用之前确实要进行条件检查,但这是出于方法的总体目的,而不是结束递归.您还具有结束递归的条件检查,但是在递归调用之后完成.解决方案是交换顺序-取 if(iStart == iEnd)块并将其移到 if(first [iStart] == second [iStart])阻止.

You do have a condition check before your recursive call, but it's for the method's overall purpose rather than for ending recursion. You also have a condition check for ending recursion, but it's done after the recursive call. The solution is to swap their order - take the if (iStart == iEnd) block and move it to before the if (first[iStart] == second[iStart]) block.

这篇关于递归地实现equals方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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