【问题标题】:How String[] args different from String... args in the main method?主方法中的 String[] args 与 String... args 有何不同?
【发布时间】:2014-04-03 20:26:34
【问题描述】:

当我看到这两种可以在 main 方法中传递命令行参数的技术时,我感到很困惑。

我在 stackoverflow 中看到了this link,但我还是不明白。

我的疑问是这两种方式之间哪种有效。

1.首先我们调用main并将参数分配为字符串数组 2.在第二个中,我们使用变量没有参数调用 main。

【问题讨论】:

  • A String... 是语法糖。当它被传递到方法中时,它实际上被包裹在 String[] 中。
  • 语法糖??没找到你。
  • 两种情况下参数都是String数组。
  • @Satya 即用一种更“眼睛友好”的方式来写同样的东西

标签: java string main


【解决方案1】:

这意味着如果你想调用一个不是入口点的类的main方法,那就更容易了:

class MyProgram1 {
    public static void main(String[] args) {
        MyProgram2.main(new String[] {"arg1", "arg2", "arg3"})
    }
}

对比:

class MyProgram1 {
    public static void main(String[] args) {
        MyProgram2.main("arg1", "arg2", "arg3")
    }
}

【讨论】:

  • 亲爱的@Eric 哪个是有效的,当我们使用 String...args[]??
  • @Satya:这是你的主要方法。它被调用一次。您确实关心调用的效率。当您想要错误legacy array notation not allowed on variable-arity parameter 时,您使用String... args[]。当你想传递可变数量的字符串数组时,你使用String[]... args
猜你喜欢
  • 1970-01-01
  • 2010-09-23
  • 2012-10-21
  • 1970-01-01
  • 1970-01-01
  • 2011-08-25
  • 2014-02-22
  • 1970-01-01
  • 2013-12-11
相关资源
最近更新 更多