Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

java - Java中Integer,AtomicInteger之间的区别(Difference between Integer, AtomicInteger in java)

When I am working with optional class of java like below

(当我使用如下所示的Java可选类时)

Integer total = null;
Optional<Integer> b = Optional.of(new Integer(10));
b.ifPresent(b -> total =b);

The above code is not working(Error: java: local variables referenced from a lambda expression must be final or effectively final) but, when I use the AtomicInteger, It will work.

(上面的代码不起作用(错误:java:从lambda表达式引用的局部变量必须是最终的或实际上是最终的),但是当我使用AtomicInteger时,它将起作用。)

Why this happens?

(为什么会这样?)

Optional<Integer> b = Optional.of(new Integer(10));
AtomicInteger total = new AtomicInteger();
b.ifPresent(b -> total.set(b));
  ask by RCvaram translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do it like this:

(您可以这样做:)

Integer total = Optional.of(new Integer(10)).orElse(null);

And if the Optional value can be nullable then:

(如果Optional值可以为空,则:)

Integer total = Optional.ofNullable(new Integer(10)).orElse(null);

Optional.ofNullable will prevent NPE in case of null value.

(Optional.ofNullable将在出现null值时阻止NPE 。)

The reason you're getting this error in the first example is that in lambda expression you're not allowed to change the reference of the local variables.

(在第一个示例中出现此错误的原因是,在lambda表达式中,您不允许更改局部变量的引用。)

That's why they need to be either declared final or effectively final.

(这就是为什么需要将它们声明为final或有效地为final的原因。)

And the reason the second example is working because here you're not changing the reference of the total variable.

(第二个示例之所以起作用的原因是,这里您没有更改total变量的引用。)

You're only updating its value using its set() method.

(您仅使用其set()方法更新其值。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...