-3

I have a question about initialization. When we initialize an array with { }, we must do it right after declaration to show compiler which type to use. Why does compiler allow diamond operator do it with 2 statements?

Integer[] array = {2,4,5};
//Integer[] array; array = {2,4,5}; - error
List<Integer> list = new ArrayList<>();
//List<Integer> list; list = new ArrayList<>(); - no error
  • I can initialize array that way. Read java documentation – Uladzislau Dukhamenka Jul 02 '19 at 15:08
  • You are right, nvm – Murat Karagöz Jul 02 '19 at 15:09
  • 2
    I'm not sure what kind of answer you expect, but mine would be "because [the languages specifies so](https://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html#jls-10.6)" – Aaron Jul 02 '19 at 15:12
  • I have no problem with array initialization. I understand that we must provide a type for compiler like "new Integer". But it is allowed to use just {} when we are writing statement in one line. Compiler understands the type of variable and make this "new Integer[]" hiddenly. The question is why diamond operator works the different way – Uladzislau Dukhamenka Jul 02 '19 at 15:14
  • The compiler checks that the array initialization has a type compatible with the declared variable, but there's no apparent reason why it couldn't do that if the variable was initialized 2 statements later. It's just that the JLS has specified that the array initialization can only appear only in a few contexts, while it hasn't specified such restrictions for the use of the diamond operator. – Aaron Jul 02 '19 at 15:19
  • I'm not sure what you're asking. Maybe you should look up how array initialization works in general and the difference between an `array` and an `ArrayList`. – dan1st Jul 02 '19 at 15:28
  • It's not 100% accurate but: by writing `Integer[] arr={}`, you tell the compiler that you are assigning `Integer`s. In general `{2,4,5}` is not a valid type. On the other hand, the diamond operator can be used if it is specified by the type. – dan1st Jul 02 '19 at 15:34

1 Answers1

2

You can do the two line way with arrays too, you just need to create a new object (and of course explicitly specify the type) when initializing.

Integer[] array;
array = new Integer[]{1, 2, 3};
pedram bashiri
  • 1,286
  • 15
  • 21