Can I pass an array as arguments to a method with variable arguments in Java?

前端 未结 5 1962
我寻月下人不归
我寻月下人不归 2020-11-22 07:52

I\'d like to be able to create a function like:

class A {
  private String extraVar;
  public String myFormat(String format, Object ... args){
    return Str         


        
5条回答
  •  再見小時候
    2020-11-22 08:11

    It's ok to pass an array - in fact it amounts to the same thing

    String.format("%s %s", "hello", "world!");
    

    is the same as

    String.format("%s %s", new Object[] { "hello", "world!"});
    

    It's just syntactic sugar - the compiler converts the first one into the second, since the underlying method is expecting an array for the vararg parameter.

    See

    • Varargs - J2SE 1.5 Documentation

提交回复
热议问题