Java provides a convenient Arrays.sort() method to sort an array of Object’s. The Objects in the array are required to implement the Comparable interface and the compareTo() method is used to compare Objects.
When an alternate sort order is needed you can do that using a Comparator which is passed to the sort() call.
The following example shows how you could sort an array of strings where the string contained a number (that should be sorted numerically) and a string (to be sorted alphabetically).
String[] array = new String[] { "34 abc", "123 dfd", "34 xyz", "12 xxx" };
Arrays.sort(array, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
// separate the number and string
String[] tokens1 = s1.split(" ");
String[] tokens2 = s2.split(" ");
// compare the number from each item
int compare = Integer.parseInt(tokens1[0]) - Integer.parseInt(tokens2[0]);
// If number same compare the string
return compare==0 ? tokens1[1].compareTo(tokens2[1]) : compare;
}
});
written by objects
\\ tags: array, comparable, comparator, sort
The following code can be used to convert a byte array (containing the bytes of a long) into a long.
public static long byteArrayToLong(byte[] bytes) {
long l = 0;
for (int i=0; i<8; i++) {
l <<= 8;
l ^= (long) bytes[i] & 0xff;
}
return l;
}
This is the reverse of “How to convert a long to a byte array“.
written by objects
\\ tags: array, byte array, conversion, long, representation
The Knuth-Morris-Pratt Pattern Matching Algorithm can be used to search a byte array.
public class KPM {
/**
* Search the data byte array for the first occurrence
* of the byte array pattern.
*/
public static int indexOf(byte[] data, byte[] pattern) {
int[] failure = computeFailure(pattern);
int j = 0;
for (int i = 0; i < data.length; i++) {
while (j > 0 && pattern[j] != data[i]) {
j = failure[j - 1];
}
if (pattern[j] == data[i]) {
j++;
}
if (j == pattern.length) {
return i - pattern.length + 1;
}
}
return -1;
}
/**
* Computes the failure function using a boot-strapping process,
* where the pattern is matched against itself.
*/
private int[] computeFailure(byte[] pattern) {
int[] failure = new int[pattern.length];
int j = 0;
for (int i = 1; i < pattern.length; i++) {
while (j>0 && pattern[j] != pattern[i]) {
j = failure[j - 1];
}
if (pattern[j] == pattern[i]) {
j++;
}
failure[i] = j;
}
return failure;
}
}
written by objects
\\ tags: array, byte, match, Pattern, search
Recent Comments