我有一些旧代码想要升级为泛型:
/**
* 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 警告我尚未参数化变量 places
和players
所以我应该将泛型添加到这段代码中,但是如何添加呢?当我添加<>
时或<Place>
对于“places”对象,它说它不是泛型,所以无论我做什么,结果都是错误的。您能告诉我如何使用泛型来现代化这部分代码吗?
谢谢
最佳答案
至于地点
...
首先,向 places
添加类型。假设每个值都是一个 Place
,每个键都是一个 String
:
public Map<String, Place> places;
(您需要两种类型:一种用于键,一种用于值。)
然后,在您的构造函数中执行相同的操作。
像这样:
public World(Adventure a) {
places = new HashMap<String, Place>();
...
}
其他字段比较简单; LinkedList
和 Collection
应该只需要一种类型,如果这是旧的旧代码,则 Adventure
(作为该代码的一部分)不需要任何。
关于java - 将原始类型重新编码为泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10927166/