我创建了一种我认为是递归的方法。

    public AssaultTeam getTeam(String teamName) {
        for(AssaultTeam team : teams){
            if(team.getName().equals(teamName)){
                return team;
            }
        }
        AssaultTeam newTeam = new AssaultTeam(teamName);
        teams.add(newTeam);
        return getTeam(teamName);
    }


'teams'是AssaultTeam的ArrayList

我以前从未使用过递归,而且不确定此方法是否可以工作。

最佳答案

是的,这是递归,递归是在调用方法本身时,您在代码的最后通过代码return getTeam(teamNames);进行操作

是的,它可以工作,但是有点奇怪,您实际上不需要此解决方案的递归

public AssaultTeam getTeam(String teamName) {
        //iterate throught the teams list - OK
        for(AssaultTeam team : teams){
            if(team.getName().equals(teamName)){
                //if found - OK
                return team;
            }
        }
        AssaultTeam newTeam = new AssaultTeam(teamName);
        teams.add(newTeam);
        //call the getTeam, which will cause another iteration to find the item - NOT GOOD
        //return getTeam(teamName);
        //just return item you just created
        return newTeam;
    }

08-17 11:20