何时更喜欢可变参数列表而不是数组?

发布于 2024-12-12 12:01:23 字数 258 浏览 1 评论 0原文

我正在实现一个 API,有一个方法,您可以传递一个路径列表,程序可以从中读取资源

public void importFrom(String... paths) {

}

我正在使用 varargs 来使用户尽可能方便地调用该方法,就像这样

obj.importFrom("/foo", "/foo/bar);

这是 varargs 的适当使用吗?还是传入数组更好?

I'm implementing an API an have a method which you pass a list of paths where the program reads resources from

public void importFrom(String... paths) {

}

I'm using varargs to make calling the method as convenient as possible to the user, like so

obj.importFrom("/foo", "/foo/bar);

Is this an appropriate use of varargs? Or is passing in an array better?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

渡你暖光 2024-12-19 12:01:23

在你的情况下 varargs 就可以了。您实际上并不需要创建要导入的路径的数组,因为除了将它们传递到 importFrom 方法之外,您不想对这些路径执行任何操作。

可变参数功能使您不必仅为了将一组值传递给一次性方法而显式创建数组,您在此处似乎确实拥有该方法。

顺便说一句,如果您愿意,您仍然可以传入数组,

public class VarargsDemo {
    public static void f(String... args) {
        for (String s: args) {
            System.out.println(s);
        }
    }
    public static void main(String[] args) {
        String[] english = new String[]{"one", "two", "three"};
        f(english);
        f("uno", "dos", "tres");
    }
}

因为行为是相同的,所以差异归结为您希望方法签名“说”什么(可能是次要的)问题。当你声明一个方法来接受显式数组参数时,几乎就像你想强调你想要对一个数组对象进行操作,数组对象是在方法外部定义的,并且在方法外部有自己的存在和重要性,并且其中,索引之类的操作也许很重要。当使用可变参数声明方法时,就好像你在说“只要给我一堆项目”。

话又说回来,这并不一定是真的。 JVM 不知道其中的区别,它在运行时看到的只是一个数组。许多程序员不会为方法签名的意图争论不休。 Varargs 就是为了让调用变得方便。

也就是说,可变参数的主要限制是这样的参数必须是方法的最后一个。就您而言,这不是问题,但总的来说这是需要考虑的事情。

In your case varargs is just fine. You don't really need to make an array of the paths that you will be importing because there's nothing you want to do with these paths other than to pass them along to your importFrom method.

The varargs functionality saves you from having to explicitly create an array solely for the purpose of passing a collection of values to a one-off method, which you do appear to have here.

BTW, you can still pass in an array if you want to

public class VarargsDemo {
    public static void f(String... args) {
        for (String s: args) {
            System.out.println(s);
        }
    }
    public static void main(String[] args) {
        String[] english = new String[]{"one", "two", "three"};
        f(english);
        f("uno", "dos", "tres");
    }
}

Because the behavior is the same, the difference comes down to a (probably minor) question of what you want the method signature to "say". When you declare a method to take an explicit array parameter, it's almost as if you want to stress that you want to operate on an array object, something that has been defined outside the method and has its own existence and importance outside the method, and one in which, perhaps, operations like indexing matter. When declaring the method with varargs, its as if you are saying "just give me a bunch of items".

Then again, this doesn't have to be true; the JVM doesn't know the difference, all it sees is an array at run time. Many programmers won't bother splitting hairs over the intent of the method signature. Varargs is all about making the calls convenient.

That said, the main limitation of varargs is that such a parameter must be the last one of the method. In your case this is not a problem, but in general it is something to consider.

吐个泡泡 2024-12-19 12:01:23

由于 varargs 参数被编译为单个数组参数,因此您通常更喜欢 varargs,因为这在某些情况下可能更方便,并且在其他情况下仍然允许传递数组。

public void importFrom(String... paths)
{
}

编译为

public void importFrom(String[] paths)
{
}

或者,您也可以使用 Iterable 来更轻松地将参数作为集合传递。

Since varargs arguments get compiled into a single array argument you could generally prefer varargs since this might be more convinient in some cases and still allows to pass an array in other cases.

public void importFrom(String... paths)
{
}

compiles into

public void importFrom(String[] paths)
{
}

Alternatively you could also use Iterable<String> to make it easier to pass the arguments as collection.

忘年祭陌 2024-12-19 12:01:23

答案取决于函数的预期用途。如果用户通常在编码时知道他想要传入哪些参数,则 varargs 是最佳选择。如果用户需要能够在运行时确定参数的数量,则数组参数将使他(或她)的生活变得更加轻松。

The answer depends on the intended use of your function. If the user typically knows at coding time which arguments he wants to pass in, varargs is the way to go. If the user needs to be able to determine the number of arguments at runtime, an array argument will make life a lot easier for him (or her).

西瓜 2024-12-19 12:01:23

我认为另一种选择是使用 List。就我个人而言,如果有多个参数或者参数是从某个地方自动处理的(例如从文件中解析),我会使用 List

如果您将在代码中手动编写参数,那么我更喜欢按照您的建议使用可变参数。

I think the other alternative is to use List<String>. Personally I would use a List if there are more than a few arguments or if arguments are automatically processed from somewhere (parsed from a file for example).

If you will be writing the arguments manually in the code, then I would prefer using the varargs as you proposed.

凝望流年 2024-12-19 12:01:23

您的方法可以接受列表或可变参数。

以下是可变参数存在原因的一些历史,假设您有多个数据和一个采用列表的方法:

String a = "hello";
int b = 50;

public void printData(List<Object> objects) {
  for (Object object : objects) {
    System.out.println(object.toString());
  }
}

然后要将数据传递给 printData() 方法,您需要从数据创建一个数组,然后将其传递给的方法。但有了 varargs,你就不需要再这样做了。

来自文档 (https://docs.oracle. com/javase/8/docs/technotes/guides/language/varargs.html):

确实必须在数组中传递多个参数,但可变参数功能会自动执行并隐藏该过程。

It's okay for your method to accept either list or varargs.

Here's a little history of why varargs exist, say you have multiple data and a method which takes a list:

String a = "hello";
int b = 50;

public void printData(List<Object> objects) {
  for (Object object : objects) {
    System.out.println(object.toString());
  }
}

Then to pass the data to the printData() method, you'd need to create an array from the data, then pass it to the method. But with varargs, you don't need to do that anymore.

From the documentation (https://docs.oracle.com/javase/8/docs/technotes/guides/language/varargs.html):

It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文