簡體   English   中英

為什么這個 String[] 在 Java 中不起作用?

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

好的,這失敗了:

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

    private String[] roles;

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

這有效:

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

    private String[] roles;

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

任何信息,將不勝感激。

謝謝。

嘗試

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

    private String[] roles;

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

String[] foo = {"bar1", "bar2"}; 如果只有聲明和初始化一起使用,則可以使用。 如果將初始化與聲明分開,則不能執行{...} 你必須new String[]{...}

數組初始化器(大括號中的位)僅在您聲明數組變量時可用,或者作為new ElementType [] initializer形式的數組創建表達式的一部分。

所以這很好:

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

這不是,因為您既沒有聲明也沒有數組創建表達式:

x = { "Blah" };

但這又很好,因為它有一個數組創建表達式:

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

上面的鏈接指向語言規范的相關部分。

你需要把是:

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

角色數組沒有通過簡單地聲明它來分配 memory。

私有字符串 [] 角色 = 新字符串 [1]; // 如果你只知道一個元素

公共 MyLoginBean() {
字符串[] blah = {"用戶"};

或者

私有字符串 [] 角色;

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM