How to implement infinity in Java?

后端 未结 10 1303
别跟我提以往
别跟我提以往 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:43

    Since the class Number is not final, here is an idea, that I don't find yet in the other posts. Namely to subclass the class Number.

    This would somehow deliver an object that can be treated as infinity for Integer, Long, Double, Float, BigInteger and BigDecimal.

    Since there are only two values, we could use the singleton pattern:

    public final class Infinity extends Number {
        public final static Infinity POSITIVE = new Infinity(false);
        public final static Infinity NEGATIVE = new Infinity(true);
        private boolean negative;
        private Infinity(boolean n) {
            negative = n;
        }
    }
    

    Somehow I think the remaining methods intValue(), longValue() etc.. should then be overriden to throw an exceptions. So that the infinity value cannot be used without further precautions.

提交回复
热议问题