Can java method arguments be collections of declared size?

Is there a way in java to declare a method argument, i.e. some kind of collection, but with a finite size?

For example, something like:

public Car(String colour, Wheel[4])

assuming that the car can be built with color and exactly 4 wheels. (Obviously, this specific example can be implemented by changing the method for listing through 4 wheels as separate parameters, but this does not scale)

It seems that similar restrictions should be expressed through method headings, but I just cannot think how Java will allow it.

+3
source share
4 answers

, . , - , , , , . (, Code Contracts in.NET, , ... .)

+5

Wheel[4] , .

+2

. :

public Car(String colour, Wheel[] wheels){
    if (wheels == null)
        throw new NullPointerException("The wheels is null.");
    if (wheels.length != 4)
        throw new IllegalArgumentException("The length of wheels is "+wheels.length);
...
}
+1

cofoja - http://code.google.com/p/cofoja/ /.

@Requires("wheels.length == 4")
public Car(String colour, Wheel[] wheels)
0

Source: https://habr.com/ru/post/1790154/


All Articles