简体   繁体   中英

Java - recursive generic type definitions

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.

<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);
  }
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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