Link to home
Start Free TrialLog in
Avatar of Nargzul
Nargzul

asked on

Java array with direct adressing (={...})

Hi there
Did someone know why the first code doesn't work?
public class DealProposition {
    public Deal[] dealPropList;
    public DealProposition(Deal d1, Deal d2) {
        dealPropList = {d1, d2};//Doesn't work???? "Illegal start of expression"
    }
}
 
 
public class DealProposition {
    public DealProposition(Deal d1, Deal d2) {
        Deal[] dealPropList = {d1, d2};//Works
    }
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Kevin Cross
Kevin Cross
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Nargzul
Nargzul

ASKER

Yes it works, I don't really  understand why, but ok
Sorry I didn't do a good job of explaining.  The way I showed is the proper syntax.  Remembering you can use the literal array initialization anonymously, so needs to know the type.

public void setArray(String[] array) { }
setArray(new String[]{"1", "2", "3",});

The shorthand {"1", "2", "3",} without the type and new keyword is legal if used in line with variable (array) declaration as a valid initializer.  This is why it worked in your second case, but not in the first.

Best regars,
Kevin