已弃用的 new Double(double) 的替代方案

Alternative for deprecated new Double(double)

我正在关注 Walter Savitch 的一本书 Absolute Java。其中的示例程序包含以下几行:

Double[] d = new Double[10];
for (int i = 0; i < d.length; i++)
    d[i] = new Double(d.length - i);

我收到以下警告消息:

warning: [deprecation] Double(double) in Double has been deprecated

我认为警告消息告诉我要替换使用构造函数,因为它已被弃用,那么我应该用什么替换它?

来自 Java 9 个构造方法是 Deprecated

Deprecated. It is rarely appropriate to use this constructor. The static factory valueOf(double) is generally a better choice, as it is likely to yield significantly better space and time performance. Constructs a newly allocated Double object that represents the primitive double argument.

所以替换为:

Double.valueOf(d.length - i)

说明

您应该将其替换为:

d[i] = Double.valueOf(d.length - i);

来自其Javadoc

Deprecated.

It is rarely appropriate to use this constructor. The static factory valueOf(double) is generally a better choice, as it is likely to yield significantly better space and time performance.

一般来说,valueOf 并不总是被强制为 return 一个 new 实例。它可以利用内部缓存并重新使用之前创建的值,这使其速度更快。例如,如果您创建数百个 1.0.


备注

您首先使用 Double[] 是否有特定原因?如果没有,请改用 double[]。与它们的对象包装器相比,原语更快并且内存开销更少。

那么你的代码就是:

double[] d = new double[10];
for (int i = 0; i < d.length; i++)
    d[i] = d.length - i;

顺便说一下,您最好不要遗漏大括号。即使你的循环只是一行。这是一个非常常见的错误来源,很难找到。

还有,你的变量命名不太好。什么是 d?尝试给它取一个能反映其实际含义的名称。例如 ages 如果它存储人的年龄。如果您没有特定的东西,可以使用 values。这已经比 d 更好了。特别是因为它是复数,所以很明显它是一个多值数组。

double[] values = new double[10];
for (int i = 0; i < values.length; i++) {
    values[i] = values.length - i;
}