2012-06-07 30 views
0

我有一些舊的代碼,我想升級到仿製藥:重新編碼原始類型,以仿製藥

/** 
    * Places in this World 
    */ 
    public Map places; 

    /** 
    * Players watching this World 
    */ 
    public Collection players; 

    /** 
    * A reference to the Adventure using this World 
    */ 
    public Adventure owner; 

    /** 
    * Create a World. `a' is a reference to the Frame itself. 
    * This reference is used when loading images and sounds. 
    * 
    * @param a An instance of adventure. 
    */ 
    public World(Adventure a) { 
    places = new HashMap(); 
    players = new LinkedList(); 
    owner = a; 
    } 

我的IDE警告我說,我沒有參數化的變量placesplayers所以我應該泛型添加到這個代碼但是如何?當我將<><Place>添加到「位置」對象時,它表示它不是泛型,但是我做它會導致錯誤。你能告訴我如何將這部分代碼現代化爲使用泛型?

感謝

回答

4

至於places ...

首先,添加類型places。假設每個值是Place,每個關鍵是String

public Map<String, Place> places; 

(您需要兩種類型:一爲鍵和一個值)

然後,在你的構造,做一樣的東西。

像這樣:

public World(Adventure a) { 
    places = new HashMap<String, Place>(); 
    ... 
} 

其他領域更簡單; LinkedListCollection應該只需要一種類型,如果這是舊的舊代碼,則Adventure(作爲該代碼的一部分)將不需要任何類型。

+0

很好,它的工作原理。我不必更改冒險宣言,並按照您現在正在使用的其他對象的建議而不發出警告。謝謝! –

2

當我添加<><Place>places對象,然後它說,它沒有泛型

既然你不告訴我們確切的代碼,既沒有確切的錯誤信息,只能猜測......也許你在places(它在語法上不正確)後面加了它,或者你只給Map(它需要兩個:鍵和值)添加一個通用類型參數?

正確的方法是

public Map<KeyType, Place> places; 

其中KeyType代表您要使用的密鑰的類型。一旦你改變了這個聲明,您還需要更新的地圖類型的所有其他引用,就像

places = new HashMap<KeyType, Place>(); 
... 
public Map<KeyType, Place> getPlaces() ... 

可能還有外部調用,例如給二傳手(如果有的話)。

1

我認爲你必須添加類型要放在地圖,並在收集的對象:

public Map<PlaceClass> places; 

public Collection<PlayerClass> players; 

public World(Adventure a) { 
    places = new HashMap<PlaceClass>(); 
    players = new LinkedList<PlayerClass>(); 
    owner = a; 
} 

凡PlaceClass和PlayerClass是您的播放器和地點對象的類名。