-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
    }
}
Marcus Junius Brutus
  • 26,087
  • 41
  • 189
  • 331

1 Answers1

2

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

System.out.println(checkIsOneOf("foo", (String) null)); // no longer NPE
Marcus Junius Brutus
  • 26,087
  • 41
  • 189
  • 331