简体   繁体   English

Java Collections.sort 用于通配符列表(List<!--?--> )

[英]Java Collections.sort for wildcard list (List<?>)

So I am trying to make a general utility function for sorting Lists of various types (mostly built-in wrappers, and Strings).所以我试图制作一个通用实用程序 function 来对各种类型的列表(主要是内置包装器和字符串)进行排序。 The sample code is below:示例代码如下:

public void sortArrays(List<?>... arr) {
    // do here
}

And it may be used as follows它可以按如下方式使用

List<Integer> a = // initialization
List<String> b = // initialization
...

sortArrays(a, b)

The function will sort varargs List and I'm planning to use Collections.sort(...) but unfortunately, it does not work on List of capture ofs. function 将对可变参数列表进行排序,我打算使用 Collections.sort(...) 但不幸的是,它不适用于捕获列表。 Is there a proper workaround or approach to what I'm trying to achieve?是否有适当的解决方法或方法来实现我想要实现的目标?

The documentation of Collections#sort states that it accepts a List<T> as a parameter, where T is defined as: Collections#sort的文档声明它接受List<T>作为参数,其中T定义为:

<T extends Comparable<? super T>>

Therefore, you should be able to define a similar generic type in your sortArrays method:因此,您应该能够在sortArrays方法中定义类似的泛型类型:

public <T extends Comparable<? super T>> void sortArrays(List<T>... arr) {
    for (List<T> list : arr) {
        Collections.sort(list);
    }
}

This solution will work if your goal is to pass in lists of a single type.如果您的目标是传递单一类型的列表,则此解决方案将起作用。 For passing lists of different types, see below.对于传递不同类型的列表,请参见下文。


There exists a hacky solution that utilizes raw types , allowing you to pass lists of different types to your sortArrays to method:存在一个利用原始类型hacky解决方案,允许您将不同类型的列表传递给sortArrays to 方法:

public static void main(String[] args) {
    List<Integer> integerList = new ArrayList<>(List.of(3, 2, 1));
    List<String> stringList = new ArrayList<>(List.of("6", "5", "4"));

    sortArrays(integerList, stringList);

    System.out.println(integerList);
    System.out.println(stringList);
}

public static void sortArrays(List<? extends Comparable>... arr) {
    for (List<? extends Comparable> list : arr) {
        Collections.sort(list);
    }
}

The output of the above snippet is:上面代码段的 output 是:

[1, 2, 3]
[4, 5, 6]

Assuming you want each list to be independently sorted by their natural ordering , you can do this by using raw generics, however that is not recommended.假设您希望每个列表按其自然顺序独立排序,您可以使用原始generics 来完成此操作,但不推荐这样做。

@SafeVarargs
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void sortArrays(List<? extends Comparable>... lists) {
    for (List<? extends Comparable> list : lists)
        Collections.sort(list);
}
List<Integer> a = Arrays.asList();
List<String> b = Arrays.asList();
List<Object> c = Arrays.asList();
sortArrays(a, b);
sortArrays(c); // compilation error because Object is not a Comparable

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

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