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)?
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)?
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.
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.
Actually you can't, but still then you can implement something like this,
For boolean returning function,
static boolean fixedArrayFuncBool(int[] arr, int lengthOfArray) {
if (arr.length == lengthOfArray) {
return true;
} else {
return false;
}
}
For integer returning function,
static int fixedArrayFuncInt(int[] arr, int lengthOfArray) {
if(arr.length == lengthOfArray) {
return lengthOfArray;
}
else {
return -1;
}
}
These function just check whether the given array is of the length that you give and return the value according to it.