2016-01-20 58 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)) { ... 
} 
相關問題