Is there a way to specify the length of an array when defining a function's return type?

Viewed 130

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?

3 Answers

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

No, length of array is not defined in type

specify the length of the array that it returns

No, declaring the return type of a method as being an array does not include a length.

But, effectively, that does not really matter. To get a similar effect:

  • Return a non-modifiable List rather than an array.
  • The calling code can simply ask the list for its size.
…
return List.of( "Bob" , "Newhart" ) ;

Of course the calling code can ask an array for its size as well as asking a list. But using a non-modifiable list locks in that size.

Define a class

Rather than hack an array or list to have certain values in certain slots to communicate meaning implicitly, define a class to represent the semantics of your values explicitly.

Records

The new Records feature of Java 16 (previewed in 14 & in 15), makes this utterly simple.

record Name ( String givenName, String surname  ) {}

So you would return an object of this type.

…
return new Name( "Bob" , "Newhart" ) ;

Point example

In your example, define a record named Point.

record Point( int x , int y ) {}

Instantiate.

…
return new Point( 7 , 42 ) ;

Access the data.

System.out.println( "x = " + myPoint.x() ) ;

x = 7

No array length can't be defined in the return type of the method.As others suggest you can do it defining a class with set of properties.

Related