簡體   English   中英

將原始類型重新編碼為泛型

[英]Recoding raw types to generics

我有一些想要升級為泛型的舊代碼:

    /**
     * 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因此我應該在此代碼中添加泛型,但是如何呢? 當我在<> places <Place>對象中添加<><Place> ,它說它不是泛型,因此我發現它是錯誤的。 您能否告訴我如何使代碼的這一部分現代化以使用泛型?

謝謝

至於places ...

首先,將類型添加到places 假設每個值都是一個Place ,並且每個鍵都是一個String

public Map<String, Place> places;

(您需要兩種類型:一種用於鍵,另一種用於值。)

然后,在您的構造函數中,執行相同的操作。

像這樣:

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

其他字段更簡單; LinkedListCollection應該只需要一種類型,並且如果這是舊的舊代碼,那么Adventure (屬於該代碼的一部分)就不需要任何類型。

當我將<><Place>添加到places對象時,它說它不是泛型

由於您沒有向我們顯示確切的代碼,也沒有確切的錯誤消息,因此只能猜測...也許是在places之后添加了它(語法上是不正確的),或者僅向Map添加了一個通用類型參數(需要兩個:鍵和值)?

正確的方法是

public Map<KeyType, Place> places;

其中KeyType代表您要使用的密鑰的類型。 更改此聲明后,還需要更新對地圖類型的所有其他引用,例如

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

可能還有外部呼叫,例如,向設置員(如果有)。

我認為您必須在地圖和集合中添加要放入的對象的類型:

public Map<PlaceClass> places;

public Collection<PlayerClass> players;

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

其中PlaceClass和PlayerClass是Player和Place對象的類名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM