将每个元素视为字节数组,并应用比较器:
import java.util.Arrays;
import java.util.Comparator;
public class SortAnyObjects {
public static void main(String[] args) {
Object[] arr = {1, 'c', '&', "z", "testing", "hello world", 'æ',
'Ã¥'};
byte[][] a = new byte[arr.length][]; // <---- The column is not initialized
for (int i = 0; i < arr.length; i++) {
if (arr[i] instanceof Integer) {
a[i] = String.valueOf((int) arr[i]).getBytes();
}
else if (arr[i] instanceof Character) {
a[i] = String.valueOf((char) arr[i]).getBytes();
}
else { // <---- Here expand your else condition as you expect the datatypes
a[i] = ((String) arr[i]).getBytes();
}
}
Arrays.sort(a, new Comparator<byte[]>() {
@Override
public int compare(
final byte[] o1,
final byte[] o2
) {
if (o1 == null) {
return 1;
}
if (o2 == null) {
return -1;
}
if (o1 == o2) {
return 0;
}
if (o2.length > o1.length) {
return compare(o2, o1);
}
for (int i = 0; i < o1.length; i++) {
if (o1[i] == o2[i]) {
continue;
}
return Byte.compare(o1[i], o2[i]);
}
return 0;
}
});
System.out.println(Arrays.toString(a));
for (int i = 0; i < a.length; i++) {
System.out.println(new String(a[i]));
}
}
}