Understanding the Basics of Generics Sorting

时光毁灭记忆、已成空白 提交于 2020-01-05 20:28:50

问题


There are a number of question on Stack Overflow about sorting Generics; however, I am interested in sorting Generics in the simplest way: nothing nested. The code I have below is an attempt to sort a generic set - or, list - of elements.

List<E> l = new LinkedList<>(arbSet);
Collections.sort(l);

arbSet is just a set of elements: Set<E> arbSet.

Clearly, this is problematic - it shouldn't work. To make sure I know this, Eclipse gives me the following for my attempt to call .sort:

Bound mismatch: The generic method sort(List < T >) of type Collections is not applicable for the arguments (List < E >). The inferred type E is not a valid substitute for the bounded parameter < T extends Comparable < ? super T >>

So, I do a bit of documentation consultation, looking at sort's specifications.

As a result, I attempt to ensure that sort knows E extends Comparable:

The first line now looking like:

List<E extends Comparable<? super E>> l = new LinkedSet<>(arbSet);

Now, Eclipse states :

Syntax error on token "extends", , expected

What am I missing? I feel like this is a very basic example and that I am just missing something "palm-to-face" esque. Just to simplify it even further, all arbSet elements are elements which implement the Comparable interface.


回答1:


You can use Collections.sort() only if you provide a custom Comparator or if the elements you are trying to sort implement the Comparable interface. So it depends on what elements are stored in arbSet.

For example, if you wanted to create a method that accepts a set, and returns a list with the set elements sorted, you would do something like this:

static <E extends Comparable<E>> List<E> sortedListFrom(Set<E> set) {
    List<E> l = new LinkedList<>(set);
    Collections.sort(l);
    return l;
}

Edit:

If you want to do this inside a constructor you have two options:

  1. Declare the type E just before the constructor. Of course, this won't do much, since list is lost after the constructor finishes.

    class Test {
        <E extends Comparable<E>> Test(Set<E> arbSet) {
            List<E> list = new LinkedList<>(arbSet);
            Collections.sort(list);
            System.out.println(list);
        }
    }
    
  2. Declare the type E in the class, so you can store the result in a attribute.

    class Test<E extends Comparable<E>> {
        List<E> list;
    
        Test(Set<E> arbSet) {
            this.list = new ArrayList<>(arbSet);
            Collections.sort(this.list);
            System.out.println(this.list);
        }
    }
    


来源:https://stackoverflow.com/questions/29596108/understanding-the-basics-of-generics-sorting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!