在 Java 中创建原始包装器 class 的最佳方法是什么

what is the best way to create primitive wrapper class in Java

我在 Java 中知道,下面有三种不同的方法可以将原始类型转换为相应的包装器 类。但是,如果性能至关重要,是否有任何首选方法?

Integer i = new Integer(5);
Integer i = 5;
Integer i = Integer.valueOf(5);

Integer.valueOf(int) 的 javadocs 给出了一个非常明确的建议:

If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

正如 Pshemo 在评论中所指出的,以及在本 SO thread 中所考虑的,Integer i = 5; 基本上会自动转换为 Integer i = Integer.valueOf(5);。因此,使用任何一种都不会对性能产生影响。

因此,如果性能是一个问题,只需避免使用 new Integer(5) 即可从缓存中获益。