具有强制数组大小参数的 Java 方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/934002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 14:25:38  来源:igfitidea点击:

Java Method with Enforced Array Size Parameters?

javaclassarchitecture

提问by Brock Woolf

I would like to create an initialisation method for a Java class that accepts 3 parameters:

我想为接受 3 个参数的 Java 类创建一个初始化方法:

Employee[] method( String[] employeeNames, Integer[] employeeAges, float[] employeeSalaries )
{
    Employee myEmployees[] = new Employee[SIZE];// dont know what size is

    for ( int count = 0; count < SIZE; count++)
    {
        myEmployees[count] = new Employee( employeeNames[count], employeeAges[count], employeeSalaries[count] );
    }
    return myEmployees;
}

You may notice that this code is wrong. THe SIZE variable is not defined. My problem is that I would like to pass in 3 arrays, but I would like to know if I can ensure that the three arrays are ALL of the same array size. This way the for loop will not fail, as the constructor in the for loop uses all the parameters of the arrays.

您可能会注意到这段代码是错误的。未定义 SIZE 变量。我的问题是我想传入 3 个数组,但我想知道是否可以确保这三个数组的数组大小都相同。这样 for 循环就不会失败,因为 for 循环中的构造函数使用数组的所有参数。

Perhaps Java has a different feature that can enforce a solution to my problem. I could accept another parameter called SIZE which will be used in the for loop, but that doesn't solve my problem if parameters 1 and 2 are of size 10 and the 3rd parameter is an array of size 9.

也许 Java 有一个不同的功能可以强制解决我的问题。我可以接受另一个名为 SIZE 的参数,它将在 for 循环中使用,但是如果参数 1 和 2 的大小为 10 并且第三个参数是大小为 9 的数组,这并不能解决我的问题。

So just to rehash incase I wasn't clear. How can I enforce that the 3 arguments are all arrays that contain the exact same number of elements?

所以只是为了重新讨论以防万一我不清楚。如何强制使 3 个参数都是包含完全相同元素数量的数组?

Using an extra parameter that specifies the array sizes isn't very elegant and kind of dirty. It also doesn't solve the problem the array parameters contain different sized arrays.

使用指定数组大小的额外参数不是很优雅而且有点脏。它也没有解决数组参数包含不同大小数组的问题。

回答by Jon Skeet

You can't enforce that at compile-time. You basically have to check it at execution time, and throw an exception if the constraint isn't met:

你不能在编译时强制执行。您基本上必须在执行时检查它,如果不满足约束则抛出异常:

Employee[] method(String[] employeeNames,
                  Integer[] employeeAges,
                  float[] employeeSalaries)
{
    if (employeeNames == null
        || employeeAges == null 
        || employeeSalaries == null)
    {
        throw new NullPointerException();
    }
    int size = employeeNames.length;
    if (employeesAges.length != size || employeeSalaries.length != size)
    {
        throw new IllegalArgumentException
            ("Names/ages/salaries must be the same size");
    }
    ...
}

回答by coobird

Since the arrays being passed in aren't generated until runtime, it is not possible to prevent the method call from completing depending upon the characteristics of the array being passed in as a compile-time check.

由于传入的数组直到运行时才会生成,因此无法根据作为编译时检查传入的数组的特征来阻止方法调用完成。

As Jon Skeet has mentioned, the only way to indicate a problem is to throw an IllegalArgumentExceptionor the like at runtime to stop the processing when the method is called with the wrong parameters.

正如 Jon Skeet 所提到的,指示问题的唯一IllegalArgumentException方法是在使用错误参数调用方法时在运行时抛出 an等以停止处理。

In any case, the documentation should clearly note the expectations and the "contract" for using the method -- passing in of three arrays which have the same lengths. It would probably be a good idea to note this in the Javadocs for the method.

在任何情况下,文档都应该清楚地说明使用该方法的期望和“合同”——传入三个长度相同的数组。在该方法的 Javadocs 中注明这一点可能是个好主意。

回答by Chii

A way to skirt around the problem is to create a builder, e.g., EmployeeArrayBuilder,

绕过这个问题的一种方法是创建一个构建器,例如,EmployeeArrayBuilder,

public class EmployeeArrayBuilder {
   private Integer arraySize = null;
   private String[] employeeNames;
   public EmployeeArrayBuilder addName(String[] employeeNames) {
      if (arraySize == null) {
         arraySize = employeeNames.length;
      } else if (arraySize != employeeNames.length) {
         throw new IllegalArgumentException("employeeNames needs to be " + arraySize + " in length");
      }
      this.employeeNames = employeeNames;
      return this;
   }
   public EmployeeArrayBuilder addSalaries(float[] employeeSalaries) {/* similar to above */}
   public EmployeeArrayBuilder addAges(Integer[] employeeAges) {/* similar  */}
   public Employee[] build() {
       // here, you can do what you needed to do in the constructor in question, and be sure that the members are correctly sized.
       Employee myEmployees[] = new Employee[arraySize ];// dont know what size is            
       for ( int count = 0; count < arraySize ; count++) {
            myEmployees[count] = new Employee( employeeNames[count], employeeAges[count], employeeSalaries[count] );
       }
       return myEmployees;
   }
}