简体   繁体   中英

Why doesn't this String[] work in Java?

OK, this fails:

public class MyLoginBean extends org.apache.struts.action.ActionForm {

    private String[] roles;

    public MyLoginBean() {
        this.roles  = {"User"};
    }
}

This works:

public class MyLoginBean extends org.apache.struts.action.ActionForm {

    private String[] roles;

    public MyLoginBean() {
        String[] blah  = {"User"};
    }
}

Any information would be appreciated.

Thanks.

Try

public class MyLoginBean extends org.apache.struts.action.ActionForm {

    private String[] roles;

    public MyLoginBean() {
        this.roles  = new String[]{"User"};
    }
}

the array initializer of type String[] foo = {"bar1", "bar2"}; can be used if only you have the declaration and initialization together. If you seperate the initialization from declaration, you cannot do {...} ; you'll have to new String[]{...}

Array initializers (the bit in braces) are only available at the point where you're declaring an array variable, or as part of an array creation expression of the form new ElementType [] initializer .

So this is fine:

// Variable declaration
String[] x = { "Blah" };

This isn't, because you have neither a declaration nor an array creation expression:

x = { "Blah" };

but this is fine again, as it's got an array creation expression:

x = new String[] { "Blah" };

The links above are to the relevant bits of the language specification.

You need to put is as:

private String [] roles  = {"User"};  // Only allowed at the time of declaration.

roles array does not have memory allocated by simply declaring it.

private String[] roles = new String[1]; // if you know only one element

public MyLoginBean() {
String[] blah = {"User"};

or

private String[] roles;

public MyLoginBean() {
String[] blah = new String[] {"User"};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM