Should autoboxing be avoided in Java?

前端 未结 5 1599
谎友^
谎友^ 2021-01-17 12:51

There are instances where a method expects a primitive type double and you pass a Double object as a parameter.

Since the compiler unboxes

5条回答
  •  半阙折子戏
    2021-01-17 13:26

    It's a design-choice and not trivially answered for every case.

    There are several items that could influence your decision:

    Advantages:

    • Auto-boxing and auto-unboxing can make your code easier to read:

      Leaving out all the unnecessary .doubleValue() and Double.valueOf() reduces the visual noise and can make your code easier to read.

    • Auto-boxing allows you to easily use collections of primitive values (such as a List, ...)

    Disadvantages:

    • excessive, unnecessary auto-boxing and auto-unboxing can hinder your performance.

      For example, if you have an API that returns a double and another API that expects a double, but you handle the value as a Double in between, then you're doing useless auto-boxing.

    • auto-unboxing can introduce a NullPointerException where you don't expect it:

      public void frobnicate(Double d) {
        double result = d / 2;
        // ...
      }
      
    • using collections of auto-boxed values uses a lot more memory than a comparable double[] for example.

提交回复
热议问题