This question already has answers here:
Difference between int[] array and int array[]
(26 answers)
Closed 9 years ago.
I've seen that arrays work when you declare them like this:
int[] myarray = {2,4,6,8,10}; //Notice the brackets are with the type
And when you declare them like this:
int myarray[] = {2,4,6,8,10}; //Here the brackets are with the array name
So which one is the correct way of declaring an array and what are the differences (if any) between the 1st and the 2nd.
Thanks.
There is no functional difference at all. It is however considered good practice to put the brackets with the type:
int[] myarray = {2,4,6,8,10};
There is no difference but prefer the first declaration.
You can also place the brackets after the array's name:
// this form is discouraged
float anArrayOfFloats[];
However,
convention discourages this form; the brackets identify the array type
and should appear with the type designation.
You can declare an int, a one-, and a two-dimensional array, all within a single declaration:
int i, oneD[], twoD[][];
Apart from this use case, you should prefer the early placement of brackets, although both are correct as far as Java specification is concerned.
They are identical in effect.
The alternate declaration of int myArray[] is a throwback to C, but the type is int[], so the first version int[] myArray is preferrred.
There is no difference. It's just a Syntactic sugar in array declaration.
Less confusing is the first type, probably.
Related
This question already has answers here:
Primitive arrays as a generic parameter [duplicate]
(4 answers)
Closed 1 year ago.
int is primitive type in java. Why is int[] usable as a generic type?
I can write code like this and compile it.
List<int[]> test = new ArrayList<>();
Indeed int is a primitive however an array of integers, int[], isn't.
Java Docs define an array as,
An array is a container object that holds a fixed number of values of
a single type.
As you can see an array is an object with class hierarchy as following,
java.lang.Object
java.util.Arrays
So arrays in java are basically objects of type java.util.Arrays. The same class also provides all the good operations you can perform on Arrays.
Back to your question, you're right, Java doesn't allow passing primitives as type parameter when you're using generics.
You cannot do this,
List<int> test = new ArrayList<int>();
However you can do generics with Integer class just fine,
List<Integer> test = new ArrayList<Integer>();
The reasons for not allowing primitives are discussed here on stackoverflow.
One might think, Java does support autoboxing so why not simply autobox primitives to their equivalent classes. Well that is a design choice. Primitives are efficient and cost less memory. Designers probably rightly decided to not assume autoboxing would serve equivalent efficiency.
This question already has answers here:
Arrays.asList() not working as it should?
(12 answers)
Closed 4 years ago.
I've got two pieces of code, in both the main focus is the method Arrays.asList(T... a).
In the first of them I input an Integer[], in the second I input an int[] , and - this is the part that confuses me, in the two cases, the resulting List<...> is different:
Integer[] arrayBoxed = new Integer[10];
List<Integer> list = Arrays.asList(arrayBoxed);
It's pretty short, and none of the values in arrayBoxed are set, but it works, and produces an List<Integer>.
int[] array = new int[10];
List<int[]> list = Arrays.asList(array);
In this case, for some reason, I get a List<int[]>, which is a pretty pathological construct.
Why is that?
The problem is, that given the similar input into Arrays.asList, I'd expect both of the functions to output the same (both code pieces are fully functional). However, one time the method returns List<Integer>, the other time List<int[]>.
Arrays.asList takes an array of reference types, not primitive types.
So, when you call Arrays.asList(int[]), the reference type taken is int[] (the array type), and that's why the result is List<int[]>.
Integer is a reference type, which explains why List<Integer> is the return type.
I was trying to allocate an Integer array for 100 items, why this declaration isn't valid in Java?
Integer[100] intArr1; ----- (1)
Whereas this is valid:
Integer[] intArr; ----- (2)
As (2) is valid, how much memory does it occupy? Can anyone help to explain a bit.
There are some questions in SO which resemble my question, however they are not the same, and I did look in SO before asking this question.
The first one isn't valid because that's not proper Java syntax.
The second one occupies 0 memory, as you haven't created an array. Only a reference to an array, with the reference being null.
You need a new Integer[100] there to actually create the array object.
You are mixing two different things.
One thing is the type of variable. In your case, you want to say "the type of variable intArr is array of Integers", which is this code Integer[] intArr;
In variable, which type is array of Integers you can put any array of Integers you like, no matter the size, therefore you cannot pre-defined it.
The second thing is assign to a variable.
Integer[] intArr = new Integer[10];
To initialise an array with 100 items you write:
Integer intArr1[] = new Integer[100];
Your second line of code just declares a variable, there is no size declared.
When you declare an array, you don't give it a length. You only give it a length when you initialise it.
This is just a declaration:
int[] myArray;
If you want to initialize it with an array of length 100, you do this:
myArray = new int[100];
An uninitialised array is null by default, or inaccessible if it is in a local scope.
This question already has an answer here:
Declaring an Array and altering its contents [duplicate]
(1 answer)
Closed 8 years ago.
List<Object[]> d = new ArrayList<Object[]>();
d.add({"A"});//compile error
Object [] arr = {"A"};//valid
I always thought that last 2 rows make equally operations and regulated by similar rules.
Who can it explain?
It's not about passing arguments to method. You can only use the {x} shorthand while initializing an array, such as your valid example. Anywhere else it's invalid. If you need to instantiate an array at a later time after initialization, you need to use new int[].
int[] a = {1,2}; // OK
int[] b;
b = {1,2}; // compiler error
I always thought that last 2 rows make equally operations and regulated by similar rules.
You were wrong.
Who can it explain?
I can't explain why you were wrong, but I can explain the syntax. The final line is valid because it is an initialisation, and initialisations have special syntax. If you had split it into a declaration and an assignment you would have got the same error in the assignment that you got in the second line. That syntax for a value simply does not exist in Java.
You can't use an array initializer as an argument.
In the first case
d.add({"A"});//compile error
You need to create a new instance of Object[] to serve as the method argument like this:
d.add(new Object[]{"A"});
In the second case, you create an array of Object. You can also do the similar thing:
Object [] arr = new Object[] {"A"};
Java lets you do the following because I think it maintains some compatibility with C/C++ array definition in the original design.
Object [] arr = {"A"};//valid
This question already has answers here:
Why won't declaring an array final make it immutable in Java?
(6 answers)
Why can I edit the contents of a final array in Java?
(9 answers)
Closed 9 years ago.
I tried using final keyword to array but still i can change the values, why arrays are not supporting final.
Thanks in advance
Because final applies to the array reference, not the contents.
You can modify the array content, but you can't say, reinstantiate the array.
Arrays in java are reference types. When you declare an array final, you are declaring the array object reference itself final, not the elements the array contains. So while you cannot alter the array reference, you can still alter individual elements in the array.
To get the effect you want, you'll have to use Collections.unmodifiableList or something similar.
Consider these
final int a[]={11,2};
int b[]={};
a=b;// this will compile wrong
a[1]=1;//this will compile fine
Because if you are declaring final array then it means that the array reference can not be changed but you can obviously change the content
Arrays are supported, but it's no different for any other reference variables: you can change the state of the variable, but you can't change the object that the variable refers to, here the array object. For arrays, the state are the item references.
final int[] test = new int[3];
test = new int[2]; //Error here
(final applies to the reference, not the object data)
If you need an immutable data structure, List (you can use ArrayList if desired) is where you'll want to go. If you really need it to be an array, you'll need to create your own data structure with only getter methods.
final in Java affects the variable, it has nothing to do with the object you are assigning to it.
final String[] myArray = { "hi", "there" };
myArray = anotherArray; // Error, you can't do that. myArray is final
myArray[0] = "over"; // perfectly fine, final has nothing to do with it