gpt4 book ai didi

java - 提供给 orElse() 的方法没有完全执行

转载 作者:太空狗 更新时间:2023-10-29 13:02:34 24 4
gpt4 key购买 nike

在下面的代码中,我试图理解 java-8 中提供的 Optional 的概念。我创建了以下示例来掌握 orElse() 背后的原理。执行代码后,执行了defaultMethod()的主体,并返回

new User("DEFAULT_USER", "default@gmail.com", "0000", null);

反对y。日志语句按照我的预期打印了正确的数据。

问题是,为什么没有打印 defaultMethod() 中的所有日志?引入 orElse() 只是为了返回值而不执行所提供方法的整个主体。?

代码:

 @Override
protected void onResume() {
super.onResume();

User user_1 = this.getUser_1();
User user_2 = this.getUser_2();
User user_3 = this.getUser_3();

User y = OptionalsUtils.toOptional(user_1)
.map(u1 -> this.getUser_3())
.orElse(this.defaultMethod());
Log.i(TAG_LOG, "orElse->y: " + y.getUserName());

}

private User getUser_3() {
List<String> list = new ArrayList<String>(5);
list.add("espn");
list.add("qtv");
list.add("der Spiegel");
list.add("deutsch welle");

User user = new User();
user.setUserName("johannas");
user.setUserEmailAddres("joha90@gmail.com");
user.setUserId("2345");
user.setUserFavoritesTvList(null);
return null;
}

private User defaultMethod() {
Log.w(TAG_LOG, "defaultMethod is called1");
Log.w(TAG_LOG, "defaultMethod is called2");
Log.w(TAG_LOG, "defaultMethod is called3");
Log.w(TAG_LOG, "defaultMethod is called4");
Log.w(TAG_LOG, "defaultMethod is called5");
Log.w(TAG_LOG, "defaultMethod is called5");
Log.w(TAG_LOG, "defaultMethod is called5");
Log.w(TAG_LOG, "defaultMethod is called5");

return new User("DEFAULT_USER", "default@gmail.com", "0000", null);
}

日志:

2018-12-17 12:46:15.774 20158-20158/com.example.optionals_00 W/ActMain: defaultMethod is called1
2018-12-17 12:46:15.774 20158-20158/com.example.optionals_00 W/ActMain: defaultMethod is called2
2018-12-17 12:46:15.774 20158-20158/com.example.optionals_00 W/ActMain: defaultMethod is called3
2018-12-17 12:46:15.774 20158-20158/com.example.optionals_00 W/ActMain: defaultMethod is called4
2018-12-17 12:46:15.774 20158-20158/com.example.optionals_00 W/ActMain: defaultMethod is called5
2018-12-17 12:46:15.774 20158-20158/com.example.optionals_00 W/ActMain: defaultMethod is called5
2018-12-17 12:46:15.774 20158-20158/com.example.optionals_00 I/ActMain: orElse->y: DEFAULT_USER

最佳答案

这不是与 orElse 相关的问题。 Logcat 跳过了缺少的那两行,因为它们是相同的。

如果 Logcat 检测到重复的日志,它将只显示第一个和最后一个,并且在两者之间您应该能够看到类似于此的消息:

04-16 03:24:21.591 I: uid=10085(u0_a85) xxx.yyy.zzz identical 2 lines

此行为始于 Android Studio 的 3.1 版本。一个issue was opened为了解决这个问题,因为很多人不喜欢,所以在Android Studio的3.2版本中去掉了。因此,如果您使用 Android Studio 3.03.2,则应显示所有日志,即使它们相同。

关于java - 提供给 orElse() 的方法没有完全执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53814848/

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