How to implement infinity in Java?

后端 未结 10 1301
别跟我提以往
别跟我提以往 2020-11-28 03:02

Does Java have anything to represent infinity for every numerical data type? How is it implemented such that I can do mathematical operations with it?

E.g.



        
10条回答
  •  無奈伤痛
    2020-11-28 03:44

    I'm supposing you're using integer math for a reason. If so, you can get a result that's functionally nearly the same as POSITIVE_INFINITY by using the MAX_VALUE field of the Integer class:

    Integer myInf = Integer.MAX_VALUE;
    

    (And for NEGATIVE_INFINITY you could use MIN_VALUE.) There will of course be some functional differences, e.g., when comparing myInf to a value that happens to be MAX_VALUE: clearly this number isn't less than myInf.

    There's also a library that actually has fields POSITIVE_INFINITY and NEGATIVE_INFINITY, but they are really just new names for MAX_VALUE and MIN_VALUE.

提交回复
热议问题