【发布时间】:2021-10-08 05:58:05
【问题描述】:
我正在创建一个实用程序类,用声明的类型替换泛型类型。目前使用 Apache Netbeans 12.0 作为我的 IDE,它不会在编译时假定这些类型。我不知道这是 Java 概念问题还是 Netbeans 的问题。
到目前为止,这是我的代码:
protected class BoardMap<Point, Cell> extends AbstractMap<Point, Cell>{
@Override
public Set<Map.Entry<Point, Cell>> entrySet() {
Set<Map.Entry<Point, Cell>> mapSet = new HashSet<>();
this.keySet().forEach(key -> {
mapSet.add(new AbstractMap.SimpleEntry<>(key, this.get(key)));
});
return mapSet;
}
/**]
*
* @param key Point as the Cell key positioning
* @return Returns the cell represented by key
*/
public Cell getCell(Point key) {
Iterator<Entry<Point, Cell>> i = entrySet().iterator();
if (key==null) {
while (i.hasNext()) {
Entry<Point, Cell> e = i.next();
if (e.getKey()==null)
return (Cell) e.getValue();
}
} else {
while (i.hasNext()) {
Entry<Point, Cell> e = i.next();
if (key.equals(e.getKey()))
return (Cell) e.getValue();
}
}
return null;
}
}
Point 和 Cell 这两个类(分别为 K 和 V)在扩展类时应该替换所有泛型类型,至少我是这么认为的。
但是在我的主代码中,当使用 BoardMap.get() 时,它说它的返回类型是 Object,而不是应该的 Cell。
在上图中,c.getPerimeter().add() 接受 Cell 的实例,但它表示 boardMap.getCell() 返回的是 Object 而不是 Cell,因为 BoardMap 类明确指出它应该返回。
这是 IDE 的问题还是我忘记了什么?
【问题讨论】:
标签: java oop inheritance netbeans overriding