传递一个String数组作为参数 [英] passing a String array as argument

查看:119
本文介绍了传递一个String数组作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个String数组可以声明,并以下列方式初始化:

A String array can be declared and initialized in the following way:

String[] str = {"A", "B"};

但它接受一个String数组作为参数的方法,为什么不能同样在那里使用?

but for a method which accepts a String array as argument, why can't the same be used there?

例如:如果在code以下,我调用替换显示()从显示(STR); 秀({AB}); ,它显示编译错误。为什么呢?

For example: if in the code below, i replace the call to show() from show(str); to show({"A" "B"});, it shows complier error. Why?

public class StringArray {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] str = {"A", "B"};
        show(str);
    }
    static void show(String[] s) {
        System.out.println(s[0] + s[1]);
    }
}

所列的编译错误是:

The compiler errors shown are:

StringArray.java:9: illegal start of expression
                show({"A", "B"});
                     ^
StringArray.java:9: ';' expected
                show({"A", "B"});
                      ^
StringArray.java:9: illegal start of expression
                show({"A", "B"});
                         ^
StringArray.java:9: ';' expected
                show({"A", "B"});
                          ^
StringArray.java:9: illegal start of type
                show({"A", "B"});
                               ^
StringArray.java:11: class, interface, or enum expected
        static void show(String[] s) {
               ^
StringArray.java:13: class, interface, or enum expected
        }
        ^
7 errors

此外使用显示(新的String [] {A,B}); 是允许的。如何为新的String [] {A,B} 从不同的 {A,B} 路过他们时的方法参数?
thanx提前!

Also using show(new String[] {"A", "B"}); is allowed. How is new String[]{"A", "B"} different from {"A", "B"} when passing them as method arguments? Thanx in advance!

推荐答案

语法 {A,B} (不包括新的String [] 在它前面)只能用作数组初始化前pression。在其他情况下(包括方法调用),你需要使用运营商。

The syntax {"A", "B"} (without new String[] in front of it) can only be used as an array initializer expression. In all other contexts (including method calls), you need to use the new operator.

查看阵列的 Java教程获取更多信息。

See the Java Tutorial on Arrays for more info.

这篇关于传递一个String数组作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆