-1

Is there an idiomatic way to handle null arguments in variable arguments lists (with the dot notation)?I've found it's a bit clunky when there is only one null, argument. Below code throws NPE on marked line.

public class FooMain {

    public static boolean checkIsOneOf(String value, String ... acceptedValues) {
        for (String acceptedValue : acceptedValues) {
            // do stuff
        }
       return false;
   }

    public static void main(String args[]) throws Exception {
        System.out.println(checkIsOneOf("foo", "a", null));
        System.out.println(checkIsOneOf("foo", "a"));
        System.out.println(checkIsOneOf("foo", null)); // NPE
    }
}
1
  • Check if acceptedValues is null before you iterate through the items. Commented Jan 9, 2014 at 19:52

1 Answer 1

2

A simple cast on the line marked 'NPE' solves the issue:

System.out.println(checkIsOneOf("foo", (String) null)); // no longer NPE
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.