Why can't you use shorthand array initialization of fields in Java constructors?

Ethan Turkeltaub picture Ethan Turkeltaub · Nov 28, 2011 · Viewed 9.7k times · Source

Take the following example:

private int[] list;

public Listing() {
    // Why can't I do this?
    list = {4, 5, 6, 7, 8};

    // I have to do this:
    int[] contents = {4, 5, 6, 7, 8};
    list = contents;
}

Why can't I use shorthand initialization? The only way I can think of getting around this is making another array and setting list to that array.

Answer

Peter Lawrey picture Peter Lawrey · Nov 28, 2011

When you define the array on the definition line, it assumes it know what the type will be so the new int[] is redundant. However when you use assignment it doesn't assume it know the type of the array so you have specify it.

Certainly other languages don't have a problem with this, but in Java the difference is whether you are defining and initialising the fields/variable on the same line.