Java中的数组常量初始化

时间:2013-11-11 06:05:13

标签: java arrays initialization

考虑下面的java示例代码,它想要搜索动作中允许的任务

public boolean acceptableTaskForAction(String taskName,String actionName) {


    String[] allowedActions;
    switch (taskName){
    case "Payment" :
        allowedActions = { "full-payment", "bill-payment"};

    case "Transfer" :
        allowedActions = { "transfer-to-other", "tarnsfer-to-own"};

    }

    for (String action : allowedActions){
        if (actionName.equals(action)){
            return true;
            }
    }
    return false;
}

如您所知,上述内容不会编译为Array constants can only be used in initializers

我想过定义不同的参数,所以它将是

public boolean acceptableTaskForAction(String taskName,String actionName) {


    String[] allowedActionsForPayment= { "full-payment", "payment"};
    String[] allowedActionsForTransfer= { "transfer-to-other", "tarnsfer-to-own"};
    String[] allowedActions={};
    switch (taskName){
    case "Payment" :
        allowedActions = allowedActionsForPayment;

    case "Transfer" :
        allowedActions = allowedActionsForTransfer;

    }

    for (String action : allowedActions){
        if (actionName.equals(action)){
            return true;
            }
    }
    return false;
}

您是否考虑过其他解决方案!? 您认为最佳解决方案是什么?

2 个答案:

答案 0 :(得分:4)

你可以做你喜欢的事情

String[] allowedActions;
switch (taskName){
case "Payment" :
    allowedActions = new String[] { "full-payment", "bill-payment"};
    break;
case "Transfer" :
    allowedActions = new String[] { "transfer-to-other", "tarnsfer-to-own"};
    break;
}

数组常量只能在初始化程序中使用,但您始终可以创建新的String[]并在需要时分配它。

答案 1 :(得分:1)

而不是Array,您可以安全地使用ArrayList来满足您的要求!

List<String> allowedActions = new ArrayList<String>();
switch (taskName){
    case "Payment" :
        allowedActions.add("full-payment");
        allowedActions.add("payment");
        break;
    case "Transfer" :
        allowedActions.add("transfer-to-other");
        allowedActions.add("tarnsfer-to-own");
        break;
    }
return allowedActions.contains(actionName);