简体   繁体   English

为什么这个 String[] 在 Java 中不起作用?

[英]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"}; 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[]{...}你必须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 .数组初始化器(大括号中的位)仅在您声明数组变量时可用,或者作为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.角色数组没有通过简单地声明它来分配 memory。

private String[] roles = new String[1];私有字符串 [] 角色 = 新字符串 [1]; // if you know only one element // 如果你只知道一个元素

public MyLoginBean() {公共 MyLoginBean() {
String[] blah = {"User"};字符串[] blah = {"用户"};

or或者

private String[] roles;私有字符串 [] 角色;

public MyLoginBean() {公共 MyLoginBean() {
String[] blah = new String[] {"User"}; String[] blah = new String[] {"用户"};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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