简体   繁体   English

可变参数与方法重载

[英]Varargs vs method overloading

Method overloading is used to perform tasks of differnt type under the restriction of no of variables passed (ie...,each of such has differnt types of code depending on parameters passed).方法重载用于在不传递变量的限制下执行不同类型的任务(即...,根据传递的参数,每个具有不同类型的代码)。 but what is the necessity of varargs ie..,we can pass multiple arguments .but how can we make the difference of code for no of variables passed ie.., multiple tasks under multiple arguments?但是 varargs 的必要性是什么,即..,我们可以传递多个参数。但是,对于没有传递的变量,我们如何使代码有所不同,即..多个参数下的多个任务?

varargs are a short hand for passing an array. varargs 是传递数组的简写。 eg instead of writing例如,而不是写作

public static void main(String[] args) {
   for(String arg : args)
       System.out.println(arg);

you can instead write你可以写

public static void main(String... args) {
   for(String arg : args)
       System.out.println(arg);

the main difference is that the caller can now write主要区别在于调用者现在可以写

main("hello", "world");

VARARGS is used when there is an indeterminate number of parameters (objects) needed for a method.当方法需要不确定数量的参数(对象)时,使用VARARGS A canonical example is Java's Formatter .一个典型的例子是 Java 的Formatter

An example is as such:一个例子是这样的:

String.format("My name is %s", myName);
String.format("My name is %s %s", myFirstName, myLastName);
String.format("My name is %s %s and I am %d years old", myFirstName, myLastName, myAge);

Lets suppose you want to calculate volume of quadrilateral.假设您要计算四边形的体积。 First scenario is calculating area for rectangle, it will require three parameters.第一个场景是计算矩形的面积,它需要三个参数。 second scenario will be if you are calculating area for cube that requires only one parameter and third scenario could be no value is passed.第二种情况是,如果您正在计算只需要一个参数的立方体的面积,而第三种情况可能是不传递任何值。 Lets see through an example: For illustration purpose only让我们看一个例子:仅用于说明目的

Class Volume(){

Volume(){
this (-1, -1, -1)
}
Volume(int x){
this (x, x, x)
}
volume(int x, y, z)
length = x;
breadth = y;
height = z;
}
public int getVolume(){
return length*breadth*height
}

This is known scenario and no other options are possible, but if you are unsure of number of arguments, we use varags.这是已知的场景,没有其他选项是可能的,但如果您不确定参数的数量,我们使用 varags。 In the above situation we did not use varags as they are less efficient and consume more space and its more dangerous in the sense it lets user to pass as many arguments as they want which is not the case in the above example在上述情况下,我们没有使用 varags,因为它们效率较低,消耗更多空间,而且更危险,因为它允许用户传递任意数量的参数,而在上面的示例中并非如此

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

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