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

3

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.

Leticia answered 28/11, 2011 at 20:54 Comment(2)
Your last sentence appears to be uncompleted. Making what?Scene
possible duplicate of Java: array initialization syntaxTaunt
U
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.

Ultraconservative answered 28/11, 2011 at 20:57 Comment(3)
So is int[] a value- or a reference-type?Leffen
int[] is a class. You can get the Class instance with Class intArrayClass = int[].class;Ultraconservative
That's what I was looking for. This question came about in my AP CS class, and my teacher didn't know either. I just wanted a less hacky way of declaring the contents of an array besides creating another one.Leticia
K
23

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

Kado answered 28/11, 2011 at 20:57 Comment(2)
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.Scene
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.Kado
C
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)

Constringent answered 15/8, 2016 at 5:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.