Home > Enterprise >  Can I declare a Java method with a fixed-sized array argument?
Can I declare a Java method with a fixed-sized array argument?

Time:12-22

In C I think it is possible to prototype a function with an input array with a fixed size. Can I also do this for java methods in general?

In addition, is an int[10] a different type than an int[20] (potentially for overloading purposes)?

CodePudding user response:

As albjerto's answer and the comments stated, Java offers no compile-time syntax to differentiate between parameters that are arrays of different sizes (although, at that answer states, you could check it in runtime).

The only (horrible) option for compile-time safety for this requirement I can think of is to unwrap the array and pass its elements as separate arguments. E.g.:

// so-called int[2] variant:
public void myMethod(int arg1, int arg2) {
    // Do something with the arguments
    // If you actually need an array, you could do:
    int[] arr = {arg1, arg2};
}

// so-called int[3] variant:
public void myMethod(int arg1, int arg2, int arg3) {
    // Your logic here...
}

// etc

With larger arrays this will become very cumbersome very quickly but for smaller arrays it may be a valid option.

CodePudding user response:

No, you can't enforce array sizes for method parameters.

However, if you have an array with a fixed number of parameters, I wonder if instead you have a clearly defined object type (e.g. a 3-D cartesian coordinate), and as such you can declare such an object (e.g. Point3D), use that as a parameter, and that typing is obviously enforced.

CodePudding user response:

No, you can't enforce a fixed length at compile time. The closest you can get is checking the length inside your method and throwing an exception if it does not meet your requirement.

As for the array types, no, they are the same.

  • Related