本文介绍了为什么在Java 8中有像DoubleFunction这样的基本函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只看了一下新的Java 8 ,并想知道为什么会有像


  • DoubleFunction

  • IntFunction

  • LongFunction

    $ b

    不是扩展功能。这并不意味着我无法传递函数< T,Int> ,其中 IntFunction< T> 是必需的,反之亦然?这同样适用于 * Block *供应商 * UnaryOperator

    我可以看到这样的优点,即当返回一个基元时,我不必检查 null 但缺点列表似乎要长得多这个问题与Java中原始类型不统一有关替换为 Object ,并且使用泛型擦除。

    使用函数

    ,整数> 代替 IntFunction< T> ,当最后一个有足够的缺点时:

    每个返回的 int 都被装箱 - 意味着更大的内存占用空间; 每个返回的 Integer 得到一个自动运行时检查(可以优化掉,但是是的);


    请注意,Java中的这些集合框架的问题导致人们写aw这个库名为Trove,它避开了通用接口,转而使用每种原始类型的专用集合类型。


    I just had a look at the the new Java 8 function package and wonder why there are interfaces like

    • DoubleFunction
    • IntFunction
    • LongFunction
    • ...

    which do not extend Function. Doesn't that mean I will not be able to pass a Function<T,Int> where a IntFunction<T> is required and vice versa? The same applies for *Block, *Supplier and *UnaryOperator.

    I can see the advantage that I will not have to check for null when a primitive is returned, but the list of disadvantages seem to be much longer

    解决方案

    This issue is related to the fact that primitive types in Java are not unified to be substitutable for Object, and with generic type erasure.

    Using Function<T, Integer> instead of IntFunction<T> when the last one suffices has 2 disadvantages:

    • Every returned int is boxed - meaning a larger memory footprint;
    • Every returned Integer gets an automatic runtime check (which can be optimized away, but yeah...);

    Note that these kinds of issues with the collection framework in Java have led people to write a whole library, named Trove, that eschews the generic interfaces in favor of specialized collection types for every primitive type.

    这篇关于为什么在Java 8中有像DoubleFunction这样的基本函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 02:01