代码之家  ›  专栏  ›  技术社区  ›  n002213f

使用Java数组

  •  1
  • n002213f  · 技术社区  · 16 年前
    /**
     * Testing Arrays
     * @author N002213F
     * @version 1.0
     */
    public class JavaArrays {
    
        public void processNames(String[] arg) {
            //-- patented method, stop, do not read ;)
        }
    
        public void test() {
    
            // works fine
            String[] names1 = new String[] { "Jane", "John" };
            processNames(names1);
    
            // works fine, nothing here
            String[] names2 = { "Jane", "John" };
            processNames(names2);
    
            // works again, please procced
            processNames(new String[] { "Jane", "John" });
    
            // fails, why, are there any reasons?
            processNames({ "Jane", "John" });
    
            // fails, but i thought Java 5 [vargs][1] handles this
            processNames("Jane", "John");
        }
    }
    
    3 回复  |  直到 16 年前
        1
  •  9
  •   Community Mohan Dere    9 年前
    processNames({ "Jane", "John" });
    

    这失败了,为什么,有什么原因吗?

    您没有指定类型。Java在这里不做类型推断;它希望您指定这是一个字符串数组。答案 this question 也会有帮助的

    processNames("Jane", "John"); 
    

    这也失败了,但是我认为Java 5 VARARGS处理这个问题。

    如果您想要varargs,那么您应该这样编写您的方法:

    public void processNames(String... arg)
    

    注意 ... 而不是 [] . 仅仅接受一个数组并不能使您在该方法上使用varargs。

        2
  •  1
  •   fastcodejava    16 年前

    最后一行: processNames(String ...args); 必须这样写才能让varargs工作。

        3
  •  0
  •   Fredrik    16 年前

    第三个调用是不正确的,因为您无法创建这样的数组,所以您可以像在第二个调用中那样进行。如果希望最终调用成功,则必须将进程名声明为varargs的接收者。( see here )