Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

class - Java Method with Enforced Array Size Parameters?

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

Employee[] method( String[] employeeNames, Integer[] employeeAges, float[] employeeSalaries )
{
    Employee myEmployees[] = new Employee[SIZE]; // I don't 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.

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.

How can I enforce that the 3 arguments are all arrays that contain the exact same number of elements? 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...