How to set constraints on generic types in Java?

大城市里の小女人 提交于 2019-11-28 22:25:18
nanda

Read also the discussion here: Generics and sorting in Java

Short answer, the best you can get is:

class ListObject<T extends Comparable<? super T>> {
    ...
}

But there is also reason to just use:

class ListObject<T extends Comparable> {
    ...
}

This depends on exactly what you want the compareTo method to do. Simply defining the compareTo method to take other ListObject<T> values is done by the following

public class ListObject<T> {
  public int compareTo(ListObject<T> other) {
    ...
  }
}

However if you want to actually call methods on that parameter you'll need to add some constraints to give more information about the T value like so

class ListObject<T extends Comparable<T>> {
  ...
}

Try public class ListObject<T extends U>. Only Ts which implement U (or derive from U) will be allowable substitutions.

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