BigInteger 还是不是 BigInteger?
在Java中,大多数原始类型都是有符号的(用一位来表示+/-),因此当我超出类型的限制时,我可能会得到意想不到的结果,比如负数。
有没有比使用 BigInteger 更好的解决方案,因为 BigInteger 存在性能问题,并且您需要使用类方法进行基本算术而不是语言运算符(破坏可读性)?
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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,没有更好的解决方案。如果您正在使用无法放入 long 或 double 的值,那么您将需要使用 BigInteger 等引用类型,并且 Java 不支持运算符重载。
从技术上讲,我想您可以在有符号和无符号值之间进行一些映射,但如果您的目标是干净且简单的代码,那么这根本不是可行的方法。
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 确实是这里的解决方案。在该语言中,“运算符”实际上只是固定的方法,并且可以为任意类定义。事实上,就您而言,它们已经在标准库中。因此,您不仅可以拥有特殊数字表示的功能,还可以拥有 Java 基本类型的简洁语法。
Scala 是久经沙场的,并且可以与您的 Java 代码完全互操作。
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.
仍然拥有漂亮的业务逻辑的唯一方法是使用脚本语言,将其编译为 java 类。然后在内部您可以使用 BigIntegers。
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.