If I have a method that returns an array, is there a way to specify the length of the array that it returns? Something along the lines of:
public int[2] getPoint() {
return new int[] {0, 1};
}
This would help add restrictions when overriding this method in a subclass, and make sure other classes implement this method correctly, because they will know that it must return an array of length 2 (or whatever else). Is there any way to do this?
Short answer is: no. You cannot do this with an array.
Longer answer is: if you find yourself in a situation that you need something like this, what your really need is a class with two fields. Based on the domain of your application it can be named differently, say for a graphics app you can have a Point class with x and y coordinates.
public class Point {
private final int x;
private final int y;
// the usual constructor, getters, setters and stuff
}
Or, if you don't want to create your own class for such a purpose you can use a tuple, like e.g. Pair from Apache Commons lib.
Classes are the way to provide such abstractions, describing the data structure you need with classes not only helps you get the job done, but makes the code more understandable for readers of your code including future you :-)