这么写就对了 ,这么写就实现你想要的了 ,首先T必须首先声明,其次声明了T就不能再次对他限定了
class myComparator <T > implements Comparator<T extends Person>这也是错的
个人理解,希望对你有帮助。
- package aaaa;
- import java.util.Comparator;
- import java.util.TreeSet;
- class Person{
- private String name;
- Person(String name){
- this.name = name;
- }
- public String getName(){
- return name;
- }
- }
- class Student extends Person{
- Student(String name){
- super(name);
- }
- }
- class Worker extends Person{
- Worker(String name){
- super(name);
- }
- }
- class myComparator <T extends Person> implements Comparator<T>{
- /*@Override
- public int compare(Object object1, Object object2) {
- // TODO Auto-generated method stub
- return 0;
- }*///这里为什么不对?
- @Override
- public int compare(T p1, T p2) {
- return p1.getName().compareTo(p2.getName());
- }
-
- }
- public class Demo4 {
- public static void main(String[] args) {
- TreeSet<Person> ts = new TreeSet<Person>(new myComparator());
-
- }
- }
复制代码 |