21

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.

Ethan Turkeltaub
  • 2,931
  • 8
  • 30
  • 45
  • Your last sentence appears to be uncompleted. Making *what*? – BalusC Nov 28 '11 at 21:13
  • possible duplicate of [Java: array initialization syntax](http://stackoverflow.com/questions/5387643/java-array-initialization-syntax) – A.H. Nov 28 '11 at 21:50

3 Answers3

24

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
23

Try list = new int[]{4, 5, 6, 7, 8};.

ziesemer
  • 27,712
  • 8
  • 86
  • 94
  • 6
    You're not really answering the concrete question. OP clearly asked why he can't use *shorthand* initialization, so we may assume that he's well aware that full initialization works. – BalusC Nov 28 '11 at 21:13
  • 1
    BalusC - good catch - though it is shorthand (at least compared to his work-around) - just not as short-hand as he was probably hoping for. – ziesemer Nov 28 '11 at 21:23
1

Besides using new Object[]{blah, blah....} Here is a slightly shorter approach to do what you want. Use the method below.

public static Object [] args(Object... vararg) {
    Object[] array = new Object[vararg.length];
    for (int i = 0; i < vararg.length; i++) {
        array[i] = vararg[i];
    }
    return array;
}

PS - Java is good, but it sucks in situations like these. Try ruby or python for your project if possible & justifiable. (Look java 8 still has no shorthand for populating a hashmap, and it took them so long to make a small change to improve developer productivity)

Community
  • 1
  • 1
MasterJoe
  • 2,103
  • 5
  • 32
  • 58