2017-08-01 83 views
1

我有兩個類,它們都包含ObservableList,但是填充了不同的對象。在其他的邏輯類我有一個返回我列表的合適對象的函數:Java中的泛型,通用函數

public CarTableView findCarTableView(Button button) { 
    for(CarTableView carnet : carTableViewModel.getObservableList()) { 
     if(carnet.getActionButton().equals(button)) { 
      return carnet; 
     } 
    } 

    return null; 
} 

第一類:

public class CustomerTableView extends Customer{ 

    private ObservableList<CustomerTableView> list = FXCollections.observableArrayList(); //HERE 
    private Button actionButton; 

    public CustomerTableView(String name, String surname, String city, 
          String postCode, String street, 
          String localNumber, Button actionButton) { 
     super(name, surname, city, postCode, street, localNumber); 
     this.actionButton=actionButton; 
    } 
} 

二等:

public class CarTableView extends Car{ 

    private ObservableList<CarTableView> list = FXCollections.observableArrayList(); //HERE 
    private Button actionButton; 

    public CarTableView(String brand, String engine, String yearOfProduction, 
         boolean navi, boolean available, int power, 
         Button actionButton) { 
     super(brand, engine, yearOfProduction, navi, available, power); 
     this.actionButton=actionButton; 
    } 
} 

但此功能僅適用於來自特定課程的一個對象。我發現了泛型的功能,但是我遇到了一個問題。在這個函數中,我必須使用具體的方法,這兩個類都有(getActionButton(),getObservableList()

我碰到過這樣的代碼,但編譯器告訴我這些函數的缺失,我該如何做得更好?

public <T> T findCarTableView(T t, Button button) { 
    for(T carnet : t.getObservableList()) { 
     if(carnet.getActionButton().equals(button)) { 
      return carnet; 
     } 
    } 

    return null; 
} 
+0

@Updated但仍然沒有解決我的問題 – Michael213

+1

「編譯器告訴我關於缺少這些功能」 - 你什麼意思?你有編譯錯誤嗎?什麼是確切的錯誤信息? – Jesper

+0

方法getObservableList()未定義類型T – Michael213

回答

3

你的問題是,編譯器不知道T的任何邊界,因此必須假設Object。因此t.getObservableList()無法工作,因爲該方法不存在於Object中。

爲了使這項工作提供了一個通用的接口或超類,並把它作爲一個邊界爲T

interface CommonInterface<T extends CommonInterface<T>> { 
    Collection<T> getObservableList(); 
} 

public <T extends CommonInterface<T>> T findCarTableView(T t, Button button) { 
    for(T carnet : t.getObservableList()) { 
    ... 
    } 
} 

注意,這個假設T類型的對象包含其他同類型的觀測。如果不是這樣,那麼改變你的接口和方法是這樣的:

interface CommonInterface<T> { 
    Collection<T> getObservableList(); 
} 

public <T> T findCarTableView(CommonInterface<T> t, Button button) { 
    for(T carnet : t.getObservableList()) { 
    ... 
    } 
} 
+0

這就是我一直在尋找!謝謝,我接受了答案 – Michael213

2

創建一個具有getActionButton()和getObservableList()方法的接口。 CarTableView和CustomerTableView必須實現它。

public TableView findCarTableView(TableView t, Button button) { 
    for(T carnet : t.getObservableList()) { 
     if(carnet.getActionButton().equals(button)) { 
      return carnet; 
     } 
    } 
    return null; 
} 

其中TableView是您的接口。

+0

我想過這個,但是'ObservableList's也包含不同的類型。 – Michael

+0

並使用ObservableList