Question

  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?

Was it helpful?

Solution 2

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.

OTHER TIPS

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

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top