OptionalInt与Optional< Integer> [英] OptionalInt vs Optional<Integer>
问题描述
滚动 java的文档时.util 包中,我惊讶地发现Optional<T>
和OptionalInt
彼此没有关系.这似乎很难相信,因为它表明它们是不相关的类.
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.
- 为什么它们没有公用的接口,类,子类型或某物来揭示它们之间的关系? (当您查看它们的用途时,它们是非常非常相似的类.)
- 此外,为什么需要额外的
OptionalInt
类?为什么不能只使用Optional<Integer>
?我认为这是由于int
是原始的,但没有OptionalChar
,因此这将是一个不一致的设计选择.
- 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.)
- Also, why the need for an additional
OptionalInt
class? Why can't you just useOptional<Integer>
? I thought it was due to the fact thatint
is primitive, but there is noOptionalChar
so that would be an inconsistent design choice.
推荐答案
Java 8引入了大量专门用于基元的方法.原因很可能是拳击原语会创建很多浪费的盒子".
Java 8 introduced a whole lot dedicated to primitives. The reason is most likely that boxing primitives can create a lot of waste "boxes".
例如这个
OptionalInt optionalFirst = IntStream
.range(0, 100)
.filter(i -> i % 23 > 7)
.findFirst();
在这里,结果Optional<Integer>
将不一致.同样,像ifPresent(IntConsumer consumer)
这样的方法也可以保留在IntStream
的世界中. Optional<Integer>
会强制您进行转换(如果需要,您可以轻松完成此操作)
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)
由于char
或short
或byte
都可以表示为int
,因此不需要特殊支持.缺少的是boolean
,但是由于只有2个值,因此您无法在它们中进行太多操作.
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.
这篇关于OptionalInt与Optional< Integer>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!