开发者

BigInteger or not BigInteger?

开发者 https://www.devze.com 2022-12-29 01:58 出处:网络
In Java, most of the primitive types are signed (one bit is used to represent the +/-), and therefore when I exceed the limits of the type, I can get unexpected results, like negative numbers.

In Java, most of the primitive types are signed (one bit is used to represent the +/-), and therefore when I exceed the limits of the type, I can get unexpected results, like negative numbers.

Is there any better solution than using BigInteger for this, since BigInteger has performance issues and you need to use the class methods for basic arithmetic instead 开发者_开发知识库of the language operators (ruins readability)?


No, there is not a better solution. If you are working with values that cannot fit into a long or a double then you will need to use a reference type like BigInteger, and Java does not support operator overloading.

Technically, I suppose you could have some mapping between signed and unsigned values, but if your goal is clean and simple code then this is not at all the way to go.


Scala is really the solution here. In that language "operators" are really just in-fixed methods, and can be defined for arbitrary classes. In fact in your case they already are in the standard library. So you can have the power of special number representations but the clean syntax of Java primitive types.

Scala is battle-hardened and will be fully interoperable with your Java code.


The only way for still having beautiful buisiness logic is using a script language, which you compile to java classes. Internally you can use BigIntegers then.

0

精彩评论

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

关注公众号