Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - OptionalInt vs Optional<Integer>

When scrolling through the documentation for the java.util package, I was surpised to find that Optional<T> and OptionalInt have no relationship to each other. This seems very hard to belive, as it suggests that they are unrelated classes.

  1. Why don't they have a common interface, class, are sub-types, or something to reveal the relationship they have? (They're very similar classes when you look at their uses.)
  2. Also, why the need for an additional OptionalInt class? Why can't you just use Optional<Integer>? I thought it was due to the fact that int is primitive, but there is no OptionalChar so that would be an inconsistent design choice.
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Java 8 introduced a whole lot dedicated to primitives. The reason is most likely that boxing primitives can create a lot of waste "boxes".

For example this

OptionalInt optionalFirst = IntStream
    .range(0, 100)
    .filter(i -> i % 23 > 7)
    .findFirst();

Here, an Optional<Integer> as result would be inconsistent. Also methods like ifPresent(IntConsumer consumer) then allow to stay withing the IntStream world. Optional<Integer> would force you to convert (which you can do easily if you want)

There is no need for special support for char or short or byte because all of them can be represented as int. The missing one is boolean but there is not much you can do in a stream with them since there are only 2 values.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...