I hadn't been here for fifteen years
If you print out an array of primitives, you can see the effect:-A few minutes ago, I wrote:. . . In the case of an array of primitives, the default values might be usable . . .
However, I don't understand the difference between the second and the third way. Why should one be preferred over the other, and when should I use one rather than the other?
Hello,
The only thing I can think off is to specify the type of the array....
I hadn't been here for fifteen years
Miles Davis wrote:
I understand that the first way is useful when you don't know the values you want in the array when you initialize it, and the second way is good when you do.
I hadn't been here for fifteen years
Campbell Ritchie wrote:I am afraid your replies were not at all helpful because they do not answer the OP's question.
I hadn't been here for fifteen years
Not in the example which OP gave; he gave an array of primitives where you cannot specify the type like that.A.J. Côté wrote:. . . "3 allows you to specify the type of the Array" . . .
Campbell Ritchie wrote:The difference between the first and second methods in OP's post are that one creates an array with elements and the other an empty array. You can see that so much better with arrays of reference types than of primitives. If you have code like this (from this post):-If you print that out with methods of the Arrays class you get the obvious output:-What you have here is a declaration and array initialiser later. The normal form of an array initialiser is this:-
words = new String[]{"Most", "ranchers", "want", "to", "strangle", "Campbell"};
but if you have the declaration and initialisation on the same line you are allowed to miss part of it out:-
String[] words = {"Most", "ranchers", "want", "to", "strangle", "Campbell"};
So that would have the same effect on the words array, and the second and third versions of Miles Davis' code will have the same effect.
The first line however declares and initialises the same array but does not initalise the individual elements. In the case of an array of primitives, the default values might be usable; the int[] shown will be filled with zeroes. But in the case of an array of primitives, the default values are nulls (see the thread I got the earlier code from). It is potentially dangerous, and probably poor practice, to have nulls, but you can see what happens if you try a different initialisation of that words array.-I would say try to put known values into the array; if you don't know the values get them assigned as soon as you can. Avoid arrays full of nulls as far as possible. Avoid nulls as far as possible.
Out on HF and heard nobody, but didn't call CQ? Nobody heard you either. 73 de N7GH
Consider Paul's rocket mass heater. |