Java - 递归泛型类型定义 [英] Java - recursive generic type definitions

查看:557
本文介绍了Java - 递归泛型类型定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用< E扩展可比< E>> 来创建界面 ISortableStack ,但是我不能前进。以下是做什么的?

 < E扩展了Comparable< E>> 

我试过这个,但它没有帮助。

解决方案

< E延伸Comparable< E>> 意味着 E 必须是类型,知道如何与本身进行比较,因此,递归类型定义。

  public class Comparables {

static class User实现Comparable< User> {
@Override
public int compareTo(用户用户){
return 0;
}
}

/ **
*该类不能与Collections.sort一起使用,因为
* UncomparableUser与自身无法比较。但是,请注意
*,您只是为了实现
* 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());

//使用这将导致编译器错误
// List< UncomparableUser> users = Arrays.asList(new UncomparableUser());

Collections.sort(users);
}
}


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

这篇关于Java - 递归泛型类型定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆