递归遍历arraylist [英] iterating through arraylists with recursion

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

问题描述

我编写了一种方法,该方法基本上检查两个ArrayList中的所有元素是否相等,如果相等,则返回true.我相信此方法有效,但是,我也想只使用递归而不使用任何循环来编写相同的方法,这意味着我必须替换for循环块.有什么建议或提示吗?

I have written a method that basically checks to see if all the elements in two ArrayLists are equal and if so, return true. I believe this method works, however, I'd like to also write this same method solely using recursion without using any loops, meaning that I'd have to replace the for loop block. Any suggestions or hints?

public static boolean isEqual(ArrayList<O> arrlist1, ArrayList<O> arrlist2) {
        ArrayList<O> um=new ArrayList<O>();
        ArrayList<O> um2=new ArrayList<O>();
        um=arrlist1;
        um2=arrlist2;
        boolean comp=false;
        if (um.size()==um2.size()){
            for (int i=0; i<um.size(); i++){
                if (um.get(i)==(um2.get(i)))
                    comp=true;
                else
                    comp=false;
            }
        }
        return comp;    
    }

推荐答案

递归版本:

public static boolean isEqual(ArrayList<O> arrlist1, ArrayList<O> arrlist2, int n) {
    if (arrlist1.size() == n && arrlist1.size() == arrlist2.size()) {
        return true;
    } else {
           if (arrlist1.get(n).equals(arrlist2.get(n))) {
               return isEqual(arrlist1, arrlist2, n + 1);
           }
           else {
               return false;
           }
    }
}

,它应该这样称呼:

 isEqual(arrlist1, arrlist2, 0);

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

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