为什么在Java 8中有多个版本的Optional [英] Why have multiple version of Optional in Java 8

查看:197
本文介绍了为什么在Java 8中有多个版本的Optional的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,Java 8中有许多类型的多个版本。

I noticed that, There are multiple versions of many Types in Java 8.

例如,引入的 可选 类有很多种 OptionalInt OptionalLong 等..

For example, The introduced Optional class has many flavors of OptionalInt, OptionalLong etc..

虽然可选有一个类型参数(可选< T> ),我们仍然需要一些特定的基元类型,为什么?

Although the Optional has a type Parameter (Optional<T>), we still need some specific types for primitives, Why?

我找不到以下两者之间的巨大差异:

I cannot find a BIG difference between the following:

Optional<Integer> o = Arrays.asList(1, 3, 6, 5).stream().filter(i -> i % 2 == 0).findAny();
System.out.println(o.orElse(-1));

OptionalInt oi = Arrays.stream(new int[] { 1, 3, 6, 5 }).filter(i -> i % 2 == 0).findAny();
System.out.println(oi.orElse(-1));


推荐答案

确实可选<从功能的角度来看,整数> OptionalInt 的行为非常相似。例如,以下方法之间没有功能差异:

It's true that Optional<Integer> behaves quite similar to OptionalInt from a functional point of view. For example, there is no functional difference between the following to methods:

int foo(int value) {
    return OptionalInt.of(value).orElse(4242);
}
int bar(int value) {
    return Optional.of(value).orElse(4242);
}

然而,性能和效率可能会有所不同 - 取决于具体方式使用可选类型和JIT编译器的功能。第二种方法基本上与以下方法相同:

However, there can be a difference in performance and efficiency--depending on how the optional types are used and on the capabilities of the JIT compiler. The second method is basically identical to the following method:

int baz(int value) {
    return Optional.of(Integer.valueOf(value))
        .orElse(Integer.valueOf(4242))
        .intValue();
}

正如你所看到的,由于每个方法的自动装箱调用最多将创建另外两个Integer对象。与本机类型相比,对象的创建是昂贵的,并且每个额外的对象都会增加垃圾收集的压力。

As you can see, due to auto-boxing for each method call up to two additional Integer objects will be created. Compared to native types, the creation of an object is expensive, and each additional object increases the pressure on the garbage collection.

这并不意味着,它会使大多数应用程序的差异。但它可以有所作为,如果它不存在,它会降低对Java 8 Streams的接受度。

That doesn't mean, that it will make a difference for most applications. But it can make a difference, and if it's not there, it lowers the acceptance for Java 8 Streams.

这篇关于为什么在Java 8中有多个版本的Optional的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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