java方法中的可选参数
我想制作一个需要 1 个必需参数和 1 个可选参数的方法,但我发现如何制作一个可选数组,方法是在参数 (int...b) 中制作,但这是一个数组,我想制作它只是这个值是 null 或用户输入它,我可以通过创建 2 个同名的方法来实现它,但一个具有单个参数,一个具有 2 个参数,但是可以仅使用一种方法来完成吗?
谢谢
I want to make a method that takes 1 required parameter and 1 optional parameter, but I found how to make an optional array which is by making in the parameter (int... b) but this is for an array, I want to make it just either this value is null or the user entered it, I can make it by making 2 methods of the same name but one with the single parameter and one with the 2 parameters, but can it be done with just one method?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,Java 不支持可选参数。重载的另一种替代方法(对于两个参数来说没有多大意义,但对于更多参数来说确实有意义)是使用表示所有参数的构建器类型 - 您可以为构建器提供一个构造函数,其中包含必需的参数,然后是每个可选参数的设置器,使设置器返回构建器本身。所以调用该方法就变成了这样:
No, Java doesn't support optional parameters. Another alternative to overloading (which doesn't make much sense for two parameters but does make sense for more) is to use a builder type which represents all the parameters - you can provide a constructor for the builder which contains the required parameters, and then a setter for each of the optional ones, making the setter return the builder itself. So calling the method becomes something like:
您正在寻找的是默认参数支持。 Java不具备这种能力,但它或多或少地模拟了这种能力。
一种简单的方法是使用方法重载。
另一种方法是直接识别特殊情况,然后替换默认值。
下面是 Ivo Limmen 混合这两种方法的示例:
我发现的一个非常有趣的方法是使用 Design Builder 模式。有一个示例这里
此处也是一个有趣的讨论
What you are looking for is default arguments support. Java doesn't have this capability but it more or less simulates this capability.
One simple way is to use method overloading.
Another approach is to identify special cases directly and then substitute the default values.
Here's an example of mixing both of those approaches by Ivo Limmen:
A very interesting approach I found is to use Design Builder pattern. There is an example here
There is also an interesting discussion here
在 Java 中,这是通过称为方法重载的方法来完成的。您可以创建多个具有相同名称但参数不同的方法。
例如:
您的代码的客户端可以调用其中之一。对他们来说,第二个参数似乎是可选的。
In java, this is accomplished by something called method overloading. You can create multiple methods with the same name, but different parameters.
For example:
Clients of your code can call either one. To them, it appears as if the second argument is optional.
不,这正是方法重载的用途
No, this is exactly what method overloading is for
Java 方法中的参数没有“默认”值。使用可变参数或方法重载。
There are no "default" values for parameters in Java's methods. Either use varargs or method overloading.