开发者

Can java method arguments be collections of a declared size?

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 woul开发者_运维百科d 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.)


You can wrap Wheel[4] in new class by creating specific List.


No. Check the argument at runtime to fail-fast:

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);
...
}


Now you can use cofoja - http://code.google.com/p/cofoja/ for this and other such input/output constraints.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜