I don't understand what exactly the brackets [] do in this code Integer[] while parsing new Objects
private Integer data[]=(Integer[]) new Object[10];//works fine
private Integer data[]=(Integer) new Object[10];//error
I don't understand what exactly the brackets [] do in this code Integer[] while parsing new Objects
private Integer data[]=(Integer[]) new Object[10];//works fine
private Integer data[]=(Integer) new Object[10];//error
private Integer data[]=(Integer) new Object[10]; //I'm a C programmer :)!
Is identical to:
private Integer[] data=(Integer) new Object[10];
Now you can better see that data is an array of Integers.
data is of type Integer[], you can't cast new Object[10]; to Integer if the type of the variable in the left side is Integer[].
I'll read the code for you:
Line 1:
new Object[10] - create a new array for 10 references to Object instances.
The references are all null when that has completed.(Integer []) ... - tell the compiler that it should assume the array of Object references to actually be an array of Integer references, ie an array of references to instances of Integer.private Integer data [] = ... - keep the array we just created in a private reference variable called data, and assume data references an array of Integer.Line 2:
(Integer) - tell the compiler to make one Integer reference of the array of Object instances. That can't be done, because there is no way to turn an array into only one object.To sum up:
The brackets in X [] indicate array of references to X.
And (Y) foo reads assume foo actually is an instance of type Y.
The type of the variable data is Integer[] (array of Integers). It would be clearer if you used the traditional style of declaring arrays:
private Integer[] data = ...
So, the first line casts the expression to the type of the variable (Integer[]), whereas the second line casts it to Integer, which is not the type of data, hence the compilation error.
Note that the second line, although it compiles, doesn't make much sense. You should simply use
private Integer[] data = new Integer[10];