How to check if an integer is in a given range?

前端 未结 18 1413
遥遥无期
遥遥无期 2020-11-27 03:58

Hoping for something more elegant than

if (i>0 && i<100) 
18条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 04:47

    This guy made a nice Range class.

    Its use however will not yield nice code as it's a generic class. You'd have to type something like:

    if (new Range(0, 100).contains(i))
    

    or (somewhat better if you implement first):

    class IntRange extends Range
    ....
    if (new IntRange(0,100).contains(i))
    

    Semantically both are IMHO nicer than what Java offers by default, but the memory overhead, performance degradation and more typing overall are hadly worth it. Personally, I like mdma's approach better.

提交回复
热议问题