Re: BitSet vs BigInteger (false Android doc)
Arne Vajh?j schrieb:
Not necessarily.
If the internal representation does not match
the external representations then some operations could
be expensive due to the conversion between representations
and/or complications for the operation itself.
Arne
In the present case the internal representation
is basically the same for BitSet and BigInteger.
The operations are also the same. Here is the
code for the logical xor in BigInteger and BitSet:
BigInteger:
public BigInteger xor(BigInteger val) {
int[] result = new int[Math.max(intLength(), val.intLength())];
for (int i=0; i<result.length; i++)
result[i] = (getInt(result.length-i-1)
^ val.getInt(result.length-i-1));
return valueOf(result);
}
BitSet:
public void xor(BitSet set) {
int wordsInCommon = Math.min(wordsInUse, set.wordsInUse);
if (wordsInUse < set.wordsInUse) {
ensureCapacity(set.wordsInUse);
wordsInUse = set.wordsInUse;
}
// Perform logical XOR on words in common
for (int i = 0; i < wordsInCommon; i++)
words[i] ^= set.words[i];
// Copy any remaining words
if (wordsInCommon < set.wordsInUse)
System.arraycopy(set.words, wordsInCommon,
words, wordsInCommon,
set.wordsInUse - wordsInCommon);
recalculateWordsInUse();
checkInvariants();
}
The immutable vs. mutable difference is seen in the signature
of the methods, and the use of ^ vs ^=.
There is a little speed-up in BitSet that the xor has only
to be applied to the min and not to the max array lengths
as is the case for BigInteger. But in the end the result will
also occupy max of the array lengths.
But if I need immutable BitSet I will also need to make a
copy first. So the Android comment is not true, there is
no intrinsic dependency on some representation, since both
representations are the same on the common domain of
positive integers:
http://developer.android.com/reference/java/math/BigInteger.html
That BitSet corresponds to the domain of positive integers
can be seen by the fact that BitSet has no not() operation,
whereby BigInteger has.
Bye