【问题标题】:Recoding raw types to generics将原始类型重新编码为泛型
【发布时间】:2012-06-11 05:35:54
【问题描述】:

我有一些遗留代码想要升级到泛型:

    /**
     * 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> 添加到“places”对象时,它说它不是泛型,所以我这样做结果是错误的。您能告诉我如何将这部分代码现代化为使用泛型吗?

谢谢

【问题讨论】:

    标签: java model-view-controller oop


    【解决方案1】:

    至于places...

    首先,将类型添加到places。假设每个值是一个Place,每个键是一个String

    public Map<String, Place> places;
    

    (您需要两种类型:一种用于键,一种用于值。)

    然后,在你的构造函数中,做同样的事情。

    像这样:

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

    其他字段更简单; LinkedListCollection 应该只需要一种类型,如果这是旧代码,Adventure(作为该代码的一部分)将不需要任何类型。

    【讨论】:

    • 很好,它有效。我不必更改 Adventure 声明并遵循您对其他对象的建议,它现在正在毫无警告地工作。谢谢!
    【解决方案2】:

    当我将 &lt;&gt;&lt;Place&gt; 添加到 places 对象时,它说它不是泛型

    由于您没有向我们显示确切的代码,也没有显示确切的错误消息,因此只能猜测...也许您在 places 之后添加了它(语法不正确),或者您只添加了一个泛型类型Map 的参数(需要两个:key 和 value)?

    正确的做法是

    public Map<KeyType, Place> places;
    

    其中KeyType 代表您希望使用的密钥类型。更改此声明后,您还需要更新对地图类型的所有其他引用,例如

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

    可能还有外部调用,例如到一个 setter(如果有的话)。

    【讨论】:

      【解决方案3】:

      我认为您必须添加要放入 Map 和 Collection 中的对象的类型:

      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 对象的类名。

      【讨论】:

        猜你喜欢
        • 2018-06-12
        • 1970-01-01
        • 2012-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多