开发者

comparator java <E>

开发者 https://www.devze.com 2023-02-19 18:36 出处:网络
My开发者_开发百科 question is the following, I have an interface that requires me to return java.util.Comparator <E>, my question is, how can i implement an abstract class that somehow returns a

My开发者_开发百科 question is the following, I have an interface that requires me to return java.util.Comparator <E>, my question is, how can i implement an abstract class that somehow returns a generic Comparator.


You can return a Comparator<?> and suppress the warnings.

Keep in mind that generics exist only at compile-time, except for reflection. By the time it's runtime, the JVM is operating on the raw classes. So, at runtime, all Comparators are the same type. So if you turn off the warnings and return a Comparator that just compares Object instances, it will work just as it would have in Java 1.2.


What type is the class? If you had this one way to do it non-abstractly:

For this:

class Name {
  String name;   
}

You could do this as a one off:

Comparator<Name> nameComparator = new Comparator<Name>() {
  public int compare(Name o1, Name o2) {
     return o1.name.compare(o2.name);
  } 

  public boolean equals(Object o) {
     return super.equals(o);
  }
}


I guess there is a valid reason for the interface to require you to return a Comparator<E> . You could return a Comparator with no type parameter (which is then in fact non-generic), but there is a chance that it will break somewhere.

What you could do:

Implement a generic class (=which takes a type parameter itself) and returns a generic Comparator.

public MyImpl<E> implements SomeInterface {

...
   public Comparator<E> createComparator() {
      ...
   }

}

Ignoring (suppressing) warnings, although it could work in your situation, will only give trouble in the long run and probably isn't the best way to go.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号