2016-01-20 60 views
2

我做了一个类“人物”,它有一个字符串名称。 现在我想用TreeSet比较两个对象。覆盖compareTo(T t)

public class People<T> implements Comparable<T> { 

    public TreeSet<People> treeSet; 
    public String name; 

    public People(String name) 
    { 
     treeSet = new TreeSet(); 
this.name = name; 
    } 

.....

@Override 
    public int compareTo(T y) { 

     if(this.name.equals(y.name)) blablabla; //Here I get error 
    } 

错误:

Cannot find symbol 
symbol: variable name; 
location: variable y of type T 
where T is a type variable 
T extends Object declared in class OsobaSet 

有谁知道如何解决这个问题?

+1

没有告诉编译器,这_T_类型都有_name_场。 – Berger

+0

我知道并不知道如何解决它:/ – szufi

+2

我想它应该是'implements Comparable ',因为那是你想要比较的。然后编译器知道人们有一个'name'字段... – Fildor

回答

5

通用类型Comparable接口代表将要比较的对象的类型。

这是你的榜样正确用法:

public class People implements Comparable<People> 

在这种情况下,方法的签名会

@Override 
public int compareTo(People y) { 
    if (this.name.equals(y.name)) { ... 
} 
相关问题