参数列表中的Java数组初始化 [英] Java array initialization within argument list

查看:159
本文介绍了参数列表中的Java数组初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

怎么得出的someMethod第一次调用不会编译没有被明确,它的的String []?

How come the first call to someMethod doesn't compile without being explicit that it's String[]?

它的优良使用数组初始化来创建一个String []数组,但你不能用它来传递参数。在一些其他时尚用于传递参数的出轨我怎么会想到这样的行为?花括号

It's fine to use an array initializer to create a String[] array but you can't use it to pass an argument. Are the curly braces used in some other fashion for passing arguments that derails how I'd expect this to behave?

public void someMethod(String[] arr){
    //do some magic
}

public void makeSomeMagic(){

    String[] arr = {"cat", "fish", "cow"};

    //Does not compile!
    someMethod({"cat", "fish", "cow"});

    //This compiles!
    someMethod(new String[]{"cat", "fish", "cow"});

    //This compiles!
    someMethod(arr);
}

编译器错误是:

该方法的someMethod(字符串[])在类型哞是不适用的参数(字符串,字符串,字符串)

The method someMethod(String[]) in the type Moo is not applicable for the arguments (String, String, String)

推荐答案

您只能使用 {你好,世界} 初始化符号声明数组时变量或数组创建前pression如新的String [] {...}

You can only use the { "hello", "world" } initialization notation when declaring an array variable or in an array creation expression such as new String[] { ... }.

请参阅 10.6节数组的初始化对象在Java语言中的规格:

数组初始化可在声明中指定,或作为数组创建前pression(§15.10)的一部分,创建一个数组,并提供一些初始值

这篇关于参数列表中的Java数组初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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