简体   繁体   English

可选的计数器行为

[英]Optional counter behaviour

I'am currently studying for OCP and I'm simply asking why the first optional does not increment "counter":我目前正在学习 OCP,我只是在问为什么第一个可选项不增加“计数器”:

Integer counter = 1;
Optional<Integer> optional = (Optional<Integer>) Optional.empty().orElse( Optional.of(counter +1));
System.out.println(counter); //print 1 

AtomicInteger counter2 = new AtomicInteger(1);
Optional<Integer> option = (Optional<Integer>) Optional.empty().orElse( Optional.of(counter2.getAndIncrement()));
System.out.println(counter2); // print 2

Because expression counter + 1 does not modify the counter variable itself.因为表达式counter + 1不会修改counter变量本身。 Try ++counter instead.尝试++counter代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM