I've tried to pass an initialization list {...} to a constructor and it didn't work. When I instead declared it in a method local variable (int[]) it worked flawlessly.
Why is that?
public class QuickSort {
int[] a;
public QuickSort(int[] a) {
this.a = a;
}
public static void main(String[] args) {
// ###################
// ### WORKS ##
// ###################
int[] a = {8,12,79,12,50,44,8,0,7,289,1};
QuickSort sort = new QuickSort(a);
// ###################
// ### DOESN'T WORK ##
// ###################
//QuickSort sort = new QuickSort({8,12,79,12,50,44,8,0,7,289,1});
}
}
When declaring an int[]
and assigning {1, 2, 3}
the compiler knows you want to create an int[]
as it's spelled out right there.
In the latter case where you stick the array directly into the method call you would have to use
QuickSort sort = new QuickSort(new int[] {8,12,79,12,50,44,8,0,7,289,1});
to tell the compiler what your array is.
The {}
construct is called an array initializer, and it is used to initialize an array in Java. (Reference: Section 10.6: Array Initializers from The Java Language Specification, Third Edition.)
The reason why passing {1, 2, 3}
itself is not valid is because there is no type information associated with the initializer.
Therefore, one must let the compiler know the type of the array is by writing new Type[]
, where the Type
is the type for which the array is made for.
The following are all valid use of the array initializer:
new String[] {"Hello, "World"}
new Character[] {'A', 'B'}
new Runnable[] {new Runnable() {public void run() {}}, new Runnable() {public void run() {}}
As can be seen, this notation can be used for many data types, so it's not something that is specific for integers.
As for:
int[] a = {1, 2, 3};
The reason why the above is valid is because the type information is provided to the compiler in the variable type declaration, which in this case is int[]
. What the above is implying is the following:
int[] a = new int[] {1, 2, 3};
Now, if we have new int[] {1, 2, 3}
, we are able to create a new int[]
array in place, so that can be handled as any other int[]
array would -- it's just that it doesn't have a variable name associated with it.
Therefore, the array created by new int[] {1, 2, 3}
can be sent into an method or constructor that takes a int[]
as its argument:
new Quicksort(new int[] {1, 2, 3}); // This will work.
This is probably because your initialization list has no typing information to it. Try this:
QuickSort sort = new QuickSort(new int[] {8,12,79,12,50,44,8,0,7,289,1});
You also can do like this:
public class QuickSort {
int[] a;
public QuickSort(int ... a) {
this.a = a;
}
public static void main(String[] args) {
QuickSort sort = new QuickSort(8,12,79,12,50,44,8,0,7,289,1);
}
}
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