简体   繁体   English

Java:将预定长度的数组设置为方法参数?

[英]Java: Setting an array of predetermined length as a method parameter?

I have a method that takes 5 double values and performs an action with them. 我有一个采用5个双精度值并对其执行操作的方法。 Right now the argument list is five different doubles. 现在,参数列表是五个不同的双打。 Is there any way to pass a double[] as an argument to the method but make sure its length is exactly 5? 有什么方法可以将double[]作为参数传递给方法,但要确保其长度恰好是5?

One way is this: 一种方法是:

private void myMethod(double[] args) {
    if (args.length == 5) {
        // do something
    }
}

but is there a better way? 但是有更好的方法吗?

If you know you need exactly 5 doubles, then I think you are better off asking for 5 distinct doubles. 如果您知道确切需要5个双打,那么我认为您最好选择5个不同的双打。 Having them listed out with meaningful names it will still be hard enough (even with intellisense or whatever it's called) to keep the order of the variables straight. 用有意义的名称列出它们,将仍然很难(即使使用智能感知或其他名称)也无法保持变量的顺序整齐。 If they are in an array, the user will need to consult the documentation to see which value should go in which index. 如果它们在数组中,则用户将需要查阅文档以查看哪个值应进入哪个索引。

No. You can't restrict the length of an array passed to a function. 不可以。您不能限制传递给函数的数组的长度。

If your goal is to keep the checking code out of the method so it's cleaner, you could delegate the real work to another method. 如果您的目标是将检查代码保留在该方法之外,以使其更干净,则可以将实际工作委托给另一个方法。

If your concern is the length of the parameter list you could pass a parameter object. 如果您关心的是参数列表的长度,则可以传递参数对象。

You could create a class which is a specialization of a Vector limited to 5 doubles, but it seems like overkill. 您可以创建一个类,它是Vector的专门化类,限制为5个double,但似乎有点过分。 I would just throw an exception if there are too few or too many entries in the array - this is likely a programming problem rather than a runtime exception. 如果数组中的条目太少或太多,我只会抛出一个异常-这很可能是编程问题,而不是运行时异常。

You could put your code in try-catch block. 您可以将代码放入try-catch块中。 This provides to miss an unnecessary check. 这提供了错过不必要的检查的机会。 But if something doing wrong you could avoid the problems with exception. 但是,如果发生错误,则可以避免出现异常情况。

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

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