gpt4 book ai didi

java - 为什么这个 java 递归方法不创建无限循环?

转载 作者:行者123 更新时间:2023-11-29 04:27:03 25 4
gpt4 key购买 nike

我是 android 开发的新手,在尝试阅读代码示例时,我遇到了一个从自身内部调用的方法,因此从逻辑上讲,它应该创建一个调用自身的无限循环。但事实并非如此。为什么?

在我的 MainActivity.java

 public void onWishlistSelected() {
launchUserSpecificFragment(new WishlistFragment(), WishlistFragment.class.getSimpleName(), new LoginDialogInterface() {
@Override
public void successfulLoginOrRegistration(User user) {
// If login was successful launch WishlistFragment.
onWishlistSelected(); // Why doesn't this create infine loop?
}
});
}

并调用它:

public boolean onOptionsItemSelected(MenuItem item) {

int id = item.getItemId();

if (id == R.id.action_wish_list) {
onWishlistSelected();
return true;
} else if (id == R.id.action_cart) {
onCartSelected();
return true;
}

return super.onOptionsItemSelected(item);
}

编辑

这是launchUserSpecificFragment中的代码

   private void launchUserSpecificFragment(Fragment fragment, String transactionTag, LoginDialogInterface loginListener) {
if (SettingsMy.getActiveUser() != null) {
replaceFragment(fragment, transactionTag);
} else {
DialogFragment loginDialogFragment = LoginDialogFragment.newInstance(loginListener);
loginDialogFragment.show(getSupportFragmentManager(), LoginDialogFragment.class.getSimpleName());
}
}

replaceFragment

 private void replaceFragment(Fragment newFragment, String transactionTag) {
if (newFragment != null) {
FragmentManager frgManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = frgManager.beginTransaction();
fragmentTransaction.setAllowOptimization(false);
fragmentTransaction.addToBackStack(transactionTag);
fragmentTransaction.replace(R.id.main_content_frame, newFragment).commit();
frgManager.executePendingTransactions();
} else {
Timber.e(new RuntimeException(), "Replace fragments with null newFragment parameter.");
}
}

最佳答案

onWishlistSelected 调用自身,所以这里没有无限递归。

它正在调用 launchUserSpecificFragment,它接收一个实现了 LoginDialogInterface 的匿名类的实例作为参数。

匿名类包含调用 onWishlistSelectedsuccessfulLoginOrRegistration 方法,但调用 onWishlistSelected 不一定执行该 successfulLoginOrRegistration方法。何时执行successfulLoginOrRegistration取决于launchUserSpecificFragment的逻辑。

关于java - 为什么这个 java 递归方法不创建无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45781368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com