I'm following a book by Walter Savitch called Absolute Java. A sample program in it contains the following lines:
Double[] d = new Double[10];
for (int i = 0; i < d.length; i++)
d[i] = new Double(d.length - i);
And I got the following warning message:
warning: [deprecation] Double(double) in Double has been deprecated
I believe that the warning message is telling me to replace the use of constructors since it is already deprecated, so what should I replace it with?
Deprecated. It is rarely appropriate to use this constructor.
A program element annotated @Deprecated is one that programmers are discouraged from using, typically because it is dangerous, or because a better alternative exists. Compilers warn when a deprecated program element is used or overridden in non-deprecated code.
Starting with JDK 9, APIs may be marked as deprecated for removal. This indicates that the API is eligible to be removed in the next release of the JDK platform. If your application or library consumes any of these APIs, then you should make a plan to migrate from them soon.
You should replace it with:
d[i] = Double.valueOf(d.length - i);
From its 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.
In general, valueOf
is not forced to always return a new instance. It can utilize an internal cache and re-use values created before already, which makes it faster. For example if you create hundreds of 1.0
.
Is there a specific reason you are using a Double[]
in the first place? If not, go for double[]
instead. The primitives are much faster and have less memory overhead, compared to their object wrapper.
Then your code is just:
double[] d = new double[10];
for (int i = 0; i < d.length; i++)
d[i] = d.length - i;
By the way, you should prefer to never omitt the curly braces. Even if your loop is just one line. This is a very common source for bugs that are hard to find.
Also, your variable naming is not very good. What is d
? Try to give it a name that reflects what it actually means. Like ages
if it stores person ages, for example. If you do not have something specific, maybe use values
. That is already better than just d
. Especially since it is plural, so it is clear that it is an array of multiple values.
double[] values = new double[10];
for (int i = 0; i < values.length; i++) {
values[i] = values.length - i;
}
From Java 9 constructor(s) method(s) was 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.
So replace with:
Double.valueOf(d.length - i)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With