1

Consider below sample code in java which wants to search which task are allowed in the action

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;
}

As you know the above will not compile as Array constants can only be used in initializers

I thought of defining different parameters so it will be

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;
}

Do you think of other solutions!? What do you think is the best solution?

2 Answers 2

4

You could do something like this your case

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;
}

Array constants can only be used in initializers, but you can always create a new String[] and assign it as and when required.

Sign up to request clarification or add additional context in comments.

1 Comment

Will the assignment statement above for allowedActions result in new allocations for each of the String elements of the array at run time, or only a new allocation for the String array itself (with the String elements merely referencing the String constants "full-payment" etc., which were created at compile time)?
1

Instead of Array you can use ArrayList safely for your requirement!

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.