OptionalInt与Optional< Integer> [英] OptionalInt vs Optional<Integer>

查看:686
本文介绍了OptionalInt与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.

  1. 为什么它们没有公用的接口,类,子类型或某物来揭示它们之间的关系? (当您查看它们的用途时,它们是非常非常相似的类.)
  2. 此外,为什么需要额外的OptionalInt类?为什么不能只使用Optional<Integer>?我认为这是由于int是原始的,但没有OptionalChar,因此这将是一个不一致的设计选择.
  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.

推荐答案

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)

由于charshortbyte都可以表示为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&lt; Integer&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆