我创建了一个我认为是递归的方法。
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;
}
关于java - 这是递归吗?它会起作用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17054327/