Java Method with Enforced Array Size Parameters?

前端 未结 3 1082
闹比i
闹比i 2020-12-10 16:23

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

Employee[] method( String[] employeeNames, Integer[] employeeAges         


        
3条回答
  •  隐瞒了意图╮
    2020-12-10 17:10

    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");
        }
        ...
    }
    

提交回复
热议问题