Why are there primitive functions like DoubleFunction in Java 8

前端 未结 1 1156
臣服心动
臣服心动 2020-12-04 01:08

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

  • DoubleFunction
  • IntFunction
相关标签:
1条回答
  • 2020-12-04 01:10

    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.

    0 讨论(0)
提交回复
热议问题