How to set constraints on generic types in Java?

喜欢而已 提交于 2019-12-29 04:27:10

问题


I have a generic class:

public class ListObject<T>
{
    // fields
    protected T _Value = null;
      // ..
}

Now I want to do something like the following:

ListObject<MyClass> foo = new ListObject<MyClass>();
ListObject<MyClass> foo2 = new ListObject<MyClass>();
foo.compareTo(foo2);

Question:

How can I define the compareTo() method with resprect to the generic T?

I guess I have to somehow implement a constraint on the generic T, to tell that T implements a specific interface (maybe Comparable, if that one exists).

Can anyone provide me with a small code sample?


回答1:


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> {
    ...
}



回答2:


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>> {
  ...
}



回答3:


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




回答4:


public class ListObject<T implements Comparable> {...}


来源:https://stackoverflow.com/questions/2081663/how-to-set-constraints-on-generic-types-in-java

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