简体   繁体   English

如何对同时包含字符和整数的数组进行排序?

[英]How to sort an array containing both characters and integers?

Consider the following array: 考虑以下数组:

{5,"k",2,"d",3,"e"}

How can I sort the array such that the characters and integers are each grouped together and sorted: 如何对数组进行排序,使字符和整数分别分组并排序:

{"d","e","k",2,3,5} 

You can sort an array by calling one of the sort() methods on Arrays . 您可以通过调用Arrayssort()方法之一来对Arrays进行sort()

In your case, you'd want to call sort(T[] a, Comparator<? super T> c) . 在您的情况下,您想调用sort(T[] a, Comparator<? super T> c)

Since your array is an Object[] , this means that you need to implement Comparator<Object> . 由于您的数组是一个Object[] ,这意味着您需要实现Comparator<Object>

Here is an example implementation that will sort your sample values as you want: 这是一个示例实现,可以根据需要对示例值进行排序:

public final class MixedComparator implements Comparator<Object> {
    @Override
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public int compare(Object obj1, Object obj2) {
        Class<?> class1 = obj1.getClass();
        Class<?> class2 = obj2.getClass();

        // Sort values of same type according to their natural order
        if (class1 == class2)
            return ((Comparable)obj1).compareTo(obj2);

        // Sort values of different type by class name,
        // in descending order, so `String` sorts before `Integer`
        return class2.getName().compareTo(class1.getName());
    }
}

You then use it like this: 然后,您可以像这样使用它:

Object[] arr = { 5, "k", 2, "d", 3, "e" };
Arrays.sort(arr, new MixedComparator());

System.out.println(Arrays.toString(arr));

Output: 输出:

[d, e, k, 2, 3, 5]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM