Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can java method arguments be collections of a declared size?

Tags:

java

oop

Is there a way in java to declare a method argument, that is some sort of collection, but with a finite size?

For example, something like:

public Car(String colour, Wheel[4])

suggesting that a Car can be constructed given a colour and exactly 4 wheels. (Obviously this particular example could be implemented by changing the method to enumerate through the 4 wheels as individual parameters, but that doesn't scale)

It seems like these sorts of constraints should be expressible through method headers, but I just cant think how java would allow it.

like image 679
magicduncan Avatar asked May 17 '26 03:05

magicduncan


1 Answers

No, there's nothing in the type system that allows this. You can validate at execution time, of course - which is what you'd usually have to do anyway, as otherwise it would be very hard for the language to give rules ensuring that the length of the array was exactly right. (Projects like Code Contracts in .NET would allow this sort of thing to be expressed, but that's not part of the language as such... and so doesn't need a precise specification.)

like image 127
Jon Skeet Avatar answered May 19 '26 16:05

Jon Skeet