ByteArrayComparator implements Comparator<byte[]> { @Override public int compare(byte[] o1, byte[] o2) { for (int i = 0; i < Math.min(o1.length, o2.length); i++) { if (o1[i] != o2[i]) { return (o1[i] & 0xFF) - (o2[i] & 0xFF); } } if (o1.length == o2.length) { return 0; } else if (o1.length < o2.length) { return -1; } else { return +1; } } private  ByteArrayComparator(); static ByteArrayComparator getInstance(); static int compareArrays(byte[] o1, byte[] o2); @Override int compare(byte[] o1, byte[] o2);  }
@Test public void testEquals() { assertEquals(0, comparator.compare(new byte[] {}, new byte[] {})); assertEquals(0, comparator.compare(new byte[] { 1 }, new byte[] { 1 })); assertEquals(0, comparator.compare(new byte[] { 1, 1, 1 }, new byte[] { 1, 1, 1 })); }
@Test public void testSmaller() { assertEquals(-1, comparator.compare(new byte[] {}, new byte[] { 1 })); assertEquals(-1, comparator.compare(new byte[] { 1 }, new byte[] { 1, 1 })); assertEquals(-1, comparator.compare(new byte[] { 1, 1 }, new byte[] { 1, 1, 1 })); assertEquals(-1, comparator.compare(new byte[] { 1 }, new byte[] { 2 })); assertEquals(-1, comparator.compare(new byte[] { 1, 1 }, new byte[] { 1, 2 })); assertEquals(-1, comparator.compare(new byte[] { 1, 1, 1 }, new byte[] { 1, 1, 2 })); }
@Test public void testGreater() { assertEquals(1, comparator.compare(new byte[] { 1 }, new byte[] {})); assertEquals(1, comparator.compare(new byte[] { 1, 1 }, new byte[] { 1 })); assertEquals(1, comparator.compare(new byte[] { 1, 1, 1 }, new byte[] { 1, 1 })); assertEquals(1, comparator.compare(new byte[] { 2 }, new byte[] { 1 })); assertEquals(1, comparator.compare(new byte[] { 1, 2 }, new byte[] { 1, 1 })); assertEquals(1, comparator.compare(new byte[] { 1, 1, 2 }, new byte[] { 1, 1, 1 })); }
@Test public void testConvertedLongs() { assertEquals(0, comparator.compare(Bytes.fromLong(1l), Bytes.fromLong(1l))); assertEquals(-1, comparator.compare(Bytes.fromLong(1l), Bytes.fromLong(2l))); assertEquals(1, comparator.compare(Bytes.fromLong(2l), Bytes.fromLong(1l))); for (long l1 = 0; l1 <= 1024; ++l1) { for (long l2 = 0; l2 <= 1024; ++l2) { if (l1 == l2) { assertEquals("Invalid comparison result for l1=" + l1 + " and l2=" + l2, 0, comparator.compare(Bytes.fromLong(l1), Bytes.fromLong(l2))); } else if (l1 < l2) { assertTrue("Invalid comparison result for l1=" + l1 + " and l2=" + l2, comparator.compare(Bytes.fromLong(l1), Bytes.fromLong(l2)) < 0); } else { assertTrue("Invalid comparison result for l1=" + l1 + " and l2=" + l2, comparator.compare(Bytes.fromLong(l1), Bytes.fromLong(l2)) > 0); } } } }