-1

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)?

2
  • 2
    Nope, you can't Commented Dec 22, 2021 at 10:12
  • 1
    No, Java does not have a thing like that. Commented Dec 22, 2021 at 10:12

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.