简体   繁体   English

使用Java中的varargs重载方法

[英]Method overloading using varargs in Java

The following code in Java uses varargs to overload methods. Java中的以下代码使用varargs来重载方法。

final public class Main
{
    private void show(int []a)
    {
        for(int i=0;i<a.length;i++)
        {
            System.out.print(a[i]+"\t");
        }
    }

    private void show(Object...a)
    {
        for(int i=0;i<a.length;i++)
        {
            System.out.print(a[i]+"\t");
        }

        System.out.println("\nvarargs called");
    }

    public static void main(String... args)
    {
        int[]temp=new int[]{1,2,3,4};            

        Main main=new Main();
        main.show(temp);
        main.show();         //<-- How is this possible?
    }
}

The output of the above code is as follows. 上述代码的输出如下。

1        2        3        4

varargs called

The last line main.show(); 最后一行main.show(); within the main() method invokes the show(Object...a){} method which has a varargs formal parameter. main()方法中调用show(Object...a){}方法,该方法具有varargs形式参数。 How can this statement main.show(); 这个语句怎么能是main.show(); invoke that method which has no actual arguments? 调用那个没有实际参数的方法?

main.show() invokes the show(Object... a) method and passes a zero-length array. main.show()调用show(Object... a)方法并传递零长度数组。

Varargs allows you to have zero or more arguments, which is why it is legal to call it with main.show() . Varargs允许你有零个或多个参数,这就是为什么用main.show()调用它是合法的。

Incidentally, I'd recommend that you don't embed \\n in your System.out.println statements - the ln bit in println prints a newline for you that will be appropriate for the system you're running on. 顺便提一下,我建议您不要在System.out.println语句中嵌入\\n - printlnln位会为您打印一个适合您正在运行的系统的换行符。 \\n isn't portable. \\n不可携带。

The varargs syntax basically lets you specify that there are possible parameters, right? varargs语法基本上允许您指定有可能的参数,对吧? They can be there, or cannot be there. 他们可以在那里,或者不能在那里。 That's the purpose of the three dots. 这就是三个点的目的。 When you call the method, you can call it with or without those parameters. 调用方法时,可以使用或不使用这些参数调用它。 This was done to avoid having to pass arrays to the methods. 这样做是为了避免必须将数组传递给方法。 For example, you can write: 例如,你可以写:

main.show(1, 2, 3, 4);

That will also work, because the numbers will become objects in wrapper classes. 这也可以,因为数字将成为包装类中的对象。 If you're still confused, take a look at this: http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html or this: When do you use varargs in Java? 如果你仍然感到困惑,请看一下: http//docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html或者: 你什么时候在Java中使用varargs?

main.show()调用采用NO参数,这对于匹配show(Object ... a)方法是完全有效的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM