Alternative for deprecated new Double(double) [duplicate] - java

This question already has answers here:
The constructors Integer(int), Double(double), Long(long) and so on are deprecated
(1 answer)
create a new Integer object that holds the value 1?
(2 answers)
Closed 3 years ago.
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?

Explanation
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.
Note
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)

Related

How to find sum with forEach and lambda expression in Java? [duplicate]

This question already has answers here:
Variable used in lambda expression should be final or effectively final
(9 answers)
How to sum a list of integers with java streams?
(12 answers)
Closed 4 years ago.
The following snippet does not compile. How to find the sum using forEach as shown below?
private int Sum(ArrayList<Integer> inputs) {
int sum = 0;
inputs.stream().forEach(x -> sum += x);
return sum;
}
This should do the trick:
private int Sum(ArrayList<Integer> inputs) {
return inputs.stream().mapToInt(Integer::intValue).sum();
}
EDIT :
The problem with using for-each is that it is a terminal operation, which means that it doesn't produce another intermediate stream for us to work on. The better approach would be to use mapToInt which produces an IntStream on which we can easily find the sum.
This answer is just to provide a bit more context as to why your code doesn't work and therefore allowing you to decipher the problem if it were to happen in the future.
It seems like you're a .NET user which makes it completely understandable for one to expect the code you've written to work. As in .NET the equivalent would be:
private int Sum(List<int> inputs) {
int sum = 0;
inputs.ForEach(x => sum += x);
return sum;
}
However, in java variables used in a lambda expression must be final or effectively final, for that reason the statement inputs.stream().forEach(x -> sum += x); will not compile.
Nevertheless, simply because one would expect the aforementioned code to work in C# doesn't necessarily mean it should work in Java as there are different rules.
There are solutions available to find the sum of a set of numbers using the forEach method but it's not the idiomatic approach and so should be avoided unless necessary.
The idiomatic approach is as #Nicholas K has shown.
On another note:
even in .NET the idiomatic approach would be return inputs.Sum();
as opposed to using the ForEach extension method to sum the elements of a given list.
whenever you seem to see yourself use inputs.stream().forEach(...); in java you should instead do inputs.forEach(...) as all lists have a forEach method.
method names in Java should be camelCase as opposed to PascalCasing as in C#.

Which one is preferable? [duplicate]

This question already has answers here:
Time complexity for java ArrayList
(6 answers)
Closed 6 years ago.
I am getting arraylist.get(i) every time a loop executes more than three times within the loop.
Is it advisable or shall I store it in separate variable then use it again and again? Which one is preferable performance wise?
Setting it to a variable is slightly more efficient. Accesing arrayList.get (I) is O (1) but still costs something eventhough it is really minor and insignificant.
Setting it to a variable is more readable in my opinion.
It's always a good approach to write readable and maintainable code. Since you question is very broad so expect broad answers as well.
List<Integer> integerList = new ArrayList<>();
for (int i=0;i<integerList.size();i++) {
Integer integerValue = integerList.get(i);
// make sure integerValue is not null.
// Thanks #Tom for pointing this out
System.out.println (integerValue);
// Do operations
System.out.println (integerValue);
// Do more operations
System.out.println (integerValue);
}
Now this is one time assignment but you can use it at multiple times. Now, for instance, you have to change the logic of program so that you want to get always i+1, it will be easy for you to change only once, not multiple times.
As others mentioned, getting object one time is slightly more efficient. Of course most of times this won't produce any problems and you can't notice any differences.
Logically because it's an O(1) operation, it shouldn't cause any differences at all, but because it calls a function of an object of type ArrayList , It's less cache friendly and direct memory reference maybe needed. Still the difference is very little.
declaring and assigning a variable once like String myString = arraylist.get(i); will be marginally faster than calling arraylist.get(i) multiple times.
Once you've done this you can call any methods on the myString instance.
I assume that arraylist is of type ArrayList<String>.
you may want to include a null check in your loop as well:
for(int i = 0; i < arraylist.size(); i++){
String myString = arraylist.get(i);
if(myString != null){
//any calls to methods on myString
}
}

Which is the correct way to represent an entire array within a for loop?

For example lets say I've create a single dimensional array and initiate the array to 100. If I want to be able to use all the values of the array, like in a for loop, how would I do it? I found two methods below but I'm not sure which approach is recommended. Also is there any differences at all?
int[] list = new int[100];
for (int i = 0; i < list.length; i++)
or
for (int i = 0; i < 100; i++)
Which of these two syntax is more commonly used?
This is much better:
for (int i = 0; i < list.length; i++)
If you change your mind, and decide that the list needs to be of length 150 instead, then the rest of your code will still work.
The other option requires you to change all of your for loops if you change the length of the array at all.
There aren't really any other differences.
EDIT: As Manoj Sharma mentioned in his answer, there's another thing you can do:
for (int myInt : list)
This will do the iteration for you, but you can't get the index in the loop.
I'm mentioning this for completeness, but if you found this helpful, upvote his answer!
for (int i = 0; i < list.length; i++) It is dynamic condition handling, It will change according to your array length.
for (int i = 0; i < 100; i++) It is static condition handling, If you have thousands of for loop you need to change each loop condition.
Evey time make sure that you avoid hard coding in your application.
Well above answer given by #Anubian Noob is good. but java5 onward java provides enhanced for each loop which is far better than other. Even no error chance in this method. look below:
for(int i: list){
System.out.println(i);
}
this will loop through the entire array and display all the element store in an array. you can also use this method for multi dimensional array too.
It is better to store the length of the array in a variable and then use it. Instead of hard coding it in the loop or find it every time loop runs.
var arraySize = yourArray.length;
for(i;i<arraySize; i++){
//your code here.
}
In Java 8 you are much better off learning to use streams. They are more intuitive and you don't need to worry about anything like the size.
For example:
int list[] = {4, 7, 3, 9, 11};
Arrays.stream(list)...
In this case Arrays.stream knows that you have created an IntStream so you get max, min, sorted, sum etc.
You need for loop much less frequently now.

Can I declare and define variables with generated names and values? [duplicate]

This question already has answers here:
Assigning variables with dynamic names in Java
(7 answers)
Closed 8 years ago.
An example:
int x1 = 1;
int x2 = 2;
int x3 = 3;
...
int xn = n;
As you can see the name and value of the variables are generated - in this case by a counter. Is this possible?How?
I do not know how, but this is probably possible with some crazy Reflection hacking - do not try to do it, as it will produce code that is hard to maintain, hard to understand and vulnerable to hard-to-trace bugs.
Instead use Collections (do not use arrays if not absolutely needed), for example ArrayList.
Yes, it is valid Java code, but in this particular case you would just use the numbers :D

Useless variable in BigInteger class, why?

I was browsing through the Java code today and I noticed something.
int[] m = mag;
int len = m.length;
int[] xm = xInt.mag;
if (len != xm.length)
return false;
(This is in the BigInteger class, which can be found by unzipping src.zip. It's in the equals method.) Why is an entirely new variable m created when it is only used once? Why isn't the code just int len = mag.length? I saw this in another method also (bitLength), and again, m is only used once. Is there any advantage to doing this or is it just a mistake by the creators of this class?
Edit: as #usernametbd pointed out, it is used a bit later:
for (int i = 0; i < len; i++)
if (xm[i] != m[i])
return false;
But they still could have just used mag. Why would an entirely new variable be made?
In a different function (in the same class, bitLength), a new variable m is made and it's only used a single time.
Because mag is a field, m is local variable. Access to local variable may be faster, though modern JITs can create such a substitute local variable automatically.
BTW you should have tell what the method you had in mind (I found it to be equals()), and cite original source (it is available) rather than decompiled one.
A bit (few lines) futher down, they use
for (int i = 0; i < len; i++)
if (xm[i] != m[i])
return false;
So m isn't completely isolated. They certainly could've used mag instead, but it's just a design choice.
When you call length (public final member variable of Array) via reflection which is constant time operation. But it is not same in C++. You have to get first array size in bytes and after divide this result to size of int to get exact value(Maybe there is better way). I think developer has the same reflex from him C++ times and carried value into local variable to use several times.
Why is it important to you? The statement is not copying an array, just copying a reference -- a pointer. And "m" will likely be allocated into a register, whereas the JVM standard requires that "mag" must usually be refetched from the object -- the JITC can't freely optimize away field references.

Categories