Re: compare two byte[] 's



On Tue, 16 Dec 2008, Eric Sosman wrote:

Mark Space wrote:

What does bother me is the lack of utility built into arrays. Changing #equals() or #clone() now would likely be too difficult, but I don't see the harm in adding new methods. All of the very similar overloaded methods in java.util.Arrays, for example, would fit neatly into instance methods of an array class. I honestly can't figure out why this hasn't been done.

Possibly because there are so many different equivalence relations that could be candidates for "equality."

Poppy***! There is exactly one relation that makes any sense - the one specified in List.equals.

Java provides one such as an array instance method, and another as a static method of Arrays. Common Lisp has four (five? it's been a while) different built-in equality operators.

And if Java were also written by and for complete madmen, then perhaps it would too, but it isn't, and shouldn't.

I think it's pretty poor that [].equals doesn't do proper equality testing, but what i find absolutely appalling is that *Arrays.equals doesn't either*. Arrays.equals uses == as the elementwise test - fine for arrays of primitives, but completely hopeless for arrays of objects. There is a deepEquals which does the right thing, but i'd never even heard of that until five minutes ago. What on earth were the authors thinking? Perhaps i should take back the part of my remark above about java not being written by madmen ...

As a thought experiment,

byte[] b = { 2, 4, 6 };
char[] c = { 2, 4, 6 };
short[] s = { 2, 4, 6 };
int[] i = { 2, 4, 6 };
long[] l = { 2, 4, 6 };
float[] f = { 2, 4, 6 };
double[] d = { 2, 4, 6 };
Integer[] oi = {
new Integer(2), new Integer(4), new Integer(6) };
BigInteger[] bi = { new BigInteger("2"), new BigInteger("4"),
new BigInteger("6") };
Object[] o = { new Integer(2), new Long(4), new Double(6) };

Which pairs of arrays "should" be equal and which "should" be unequal?

The ones where the corresponding pair of Lists would be equal or unequal, respectively. *

We can argue about whether new Integer(2), new Short(2) and new BigInteger("2") should be equal, but that's got nothing to do with arrays. If you want to be evil, include a BigDecimal("2.0") and a BigDecimal("2.00") up there too - and if you want to be really evil, arrays of arrays.

Get every programmer everywhere to agree with your answer. ;-)

I'd be very interested to hear from anyone who thinks my assertion above (marked with the asterisk) is wrong.

tom

--
The Gospel is enlightened in interesting ways by reading Beowulf and The
Hobbit while listening to Radiohead's Hail to the Thief. To kill a dragon
(i.e. Serpent, Smaug, Wolf at the Door) you need 12 (disciples/dwarves)
plus one thief (burglar, Hail to the Thief/King/thief in the night),
making Christ/Bilbo the 13th Thief. -- Remy Wilkins
.