java - 将原始类型重新编码为泛型

标签 java model-view-controller oop

我有一些旧代码想要升级为泛型:

    /**
     * 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”对象,它说它不是泛型,所以无论我做什么,结果都是错误的。您能告诉我如何使用泛型来现代化这部分代码吗?

谢谢

最佳答案

至于地点...

首先,向 places 添加类型。假设每个值都是一个 Place,每个键都是一个 String:

public Map<String, Place> places;

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

然后,在您的构造函数中执行相同的操作。

像这样:

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

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

关于java - 将原始类型重新编码为泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10927166/

相关文章:

javascript - Dropdownlist 未使用 Angular JS 设置值

java - 如何在 JSP 中公开 bean?

c# - 仅公开派生类中的一些继承方法

c# - 为什么私有(private)字段是类型私有(private)的,而不是实例私有(private)的?

java - AP CS 实践 - OOP

java - 将单词存储到 Hashmap 中

ruby-on-rails - 使用另一个模型创建用户

java - 在 JSP 中打印数据表标题

java - 将java转换为c#的问题

java - 如何使用 gson 将对象序列化为一个元素的列表