Why is the java language structured such that in regard to my second invocation of the foo method I get a compiler error:
<I>Kai M.</I>
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
The problem is that your foo method requires an int array and that is not what you are passing it. Arrays in java are objects, so you need to create one to send. It looks to me like neither invocation will work. All objects, except Strings, need to be explicitly created with the new keyword. public class IllegalStartOfExpression{ public static void main(String [] args){ int[] x = new int[]{1, 2}; foo(x); foo(new int[]{1, 2}); } public static void foo(int[] x){ System.out.println(x[0]); } }
------------------ Brian Hoff Sun Certified Programmer for the Java� 2 Platform
If I could add something: The confusing thing about anonymous arrays (which is what we're talking about), is that at first glance it appears that an initialization list is the anonymous array: The confusing part (for me) was that I have a book that says The construct (ie: the anonymous array) returns an array reference which can be assigned, and passed as a parameter. In particular, the following two examples are equivalent: int[] intArray = {2,3,4,5}; int[] intArray = new int[] {2,3,4,5};
I thought that {2,3,4,5} was an anonymous array, but of course it's not, it's simply an initialization list, and not the anonymous array itself. So this list by itself cannot be passed to a method which expects an array.
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.