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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With