views:

170

answers:

3

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

In the BigInteger class, I have no limits and there are some helpful functions there but it is pretty depressing to convert your beautiful code to work with the BigInteger class, specially when primitive operators don't work there and you must use functions from this class.

I was wondering if you had this problem, and if you have any better solution than the BigInteger class?

Thank you.

+7  A: 

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.

danben
+1 "it is pretty depressing to convert your beautiful code to work with the BigInteger" Your beatiful code show know the order of magnituded of the values involved, and the limitations of your datatypes. Few practical use cases could overflow a long (64-bit signed integer), and these should be identifiable.
leonbloy
+1  A: 

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.

Daniel
+2  A: 

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.

Yuvi Masory
Groovy is also an option along the same lines.
Yishai
Yes, Scala is a good example for a scripting language to achive this, especially since it compiles to native Java Bytecode!
Daniel