Java 可变参数可以为空吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28271203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:18:41  来源:igfitidea点击:

Can a Java varargs be null?

javavariadic-functionsnull-check

提问by Supuhstar

I found myself checking for this and asking if it's necessary. I have code like this:

我发现自己正在检查这个并询问是否有必要。我有这样的代码:

public Object myMethod(Object... many) {
  if (many == null || many.length == 0)
    return this;
  for (Object one : many)
    doSomethingWith(one);
  return that;
}

But then I wondered... Am I being too cautious? Do I have to check if many == null? Is that ever possible in any current Java version?If so, how? If not, I'll probably keep checking, just for futureproofing in case Oracle decides it can be null one day.

但后来我想知道……我是不是太谨慎了?我必须检查many == null吗?在任何当前的 Java 版本中都可能吗?如果是这样,如何?如果没有,我可能会继续检查,以防将来 Oracle 决定它可以为空。

回答by Dave

I tried it with Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0 on Linux 3.5.0-21-generic

我试过了 Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0 on Linux 3.5.0-21-generic

Using myMethod(null)doesn't pass new Object[]{null}, it passes null. Arrays are objects in Javaand therefore nullis valid for the type Object[].

使用myMethod(null)不通过new Object[]{null},它通过null数组是 Java 中的对象,因此null对类型有效Object[]

Your nullcheck is, therefore, not overly cautious.

因此,您的空检查并不过分谨慎。