Java generics and the Number class

后端 未结 5 1565
一个人的身影
一个人的身影 2021-01-11 16:16

I want to create a method that compares a number but can have an input that is any of the subclasses of Number.

I have looked at doing this in the following manner..

5条回答
  •  情歌与酒
    2021-01-11 16:53

    Methods with are always trouble, since you can't really do anything on a Number (all the operators are defined for the children). You would need to either do a ton of instanceof for each child of Number and treat that case by casting to the subtype. Or (better I think - that's the way Sun does it) is to just have a method for each child type, possibly taking advantage of boxing/unboxing for operators like +,-,> etc. where that is possible (all wrappers, not for BigInteger/BigDecimal or any custom types).

提交回复
热议问题