Skip to content

Instantly share code, notes, and snippets.

@taichi
Created March 3, 2011 03:05
Show Gist options
  • Save taichi/852250 to your computer and use it in GitHub Desktop.
Save taichi/852250 to your computer and use it in GitHub Desktop.
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class ArrayCompare {
public static int compare(byte[] lefts, byte[] rights) {
if (lefts == rights) {
return 0;
}
if ((lefts != null) && (rights == null)) {
return 1;
}
if ((lefts == null) && (rights != null)) {
return -1;
}
int ll = lefts.length;
int rl = rights.length;
int min = Math.min(ll, rl);
for (int i = 0; i < min; i++) {
byte lb = lefts[i];
byte rb = rights[i];
if (lb < rb) {
return -1;
}
if (lb > rb) {
return 1;
}
}
return ll - rl;
}
@Test
public void testCompare() throws Exception {
assertEquals(0, compare(null, null));
assertEquals(-1, compare(null, new byte[0]));
assertEquals(1, compare(new byte[0], null));
assertEquals(-1, compare(new byte[0], new byte[1]));
assertEquals(1, compare(new byte[1], new byte[0]));
assertEquals(0, compare(new byte[] { 1 }, new byte[] { 1 }));
assertEquals(1, compare(new byte[] { 1, 2 }, new byte[] { 1, 1 }));
byte[] aa = new byte[] { 'a', 'a' };
byte[] zzzz = new byte[] { 'z', 'z', 'z', 'z' };
assertEquals(-1, compare(aa, zzzz));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment