Java - recursive generic type definitions

梦想与她 提交于 2019-12-25 17:19:18

问题


I tried to create an interface ISortableStack using <E extends comparable <E>> but I can't move forward. What does the following do?

<E extends Comparable<E>> 

I've tried this, but it doesn't help.


回答1:


<E extends Comparable<E>> means that E must be a type that knows how to compare to itself, hence, the recursive type definition.

public class Comparables {

  static class User implements Comparable<User> {
    @Override
    public int compareTo(User user) {
      return 0;
    }
  }

  /**
   * This class cannot be used with Collections.sort because an
   * UncomparableUser is not comparable with itself. However, notice
   * that you get no compiler error just for implementing
   * Comparable<String>.
   */
  static class UncomparableUser implements Comparable<String> {
    @Override
    public int compareTo(String user) {
      return 0;
    }
  }

  public static void main(String[] args) {
    List<User> users = Arrays.asList(new User());

    // Using this would cause a compiler error
    // List<UncomparableUser> users = Arrays.asList(new UncomparableUser());

    Collections.sort(users);
  }
}



回答2:


If you're asking what does this mean:

<E extends Comparable<E>> 

It means that the class 'E' passed in must implement the Comparable interface.




回答3:


The < and > characters are part of the "generic" syntax. The standard library is choke full of "generic" interfaces; take a look at the Set interface for an example.



来源:https://stackoverflow.com/questions/7131714/java-recursive-generic-type-definitions

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