【发布时间】:2015-08-07 08:38:23
【问题描述】:
只是尝试做类似的事情:
public class GameMap {
protected HashMap<Sector, Integer[]> mapping;
protected void loadMapFromFile(String fileLocation, int numPlayers) {
.
//Other stuff
.
.
case "ALIENSECT":
Integer[] someValue = {5};
mapping.put(new AlienSector(row, col), someValue);
break;
}
public justATestMethod() {
System.out.println(mapping.containsKey(new Sector(6, 'L')));
}
其中AlienSector 是Sector 的子类。
但是当我尝试在另一个班级这样做时:
mappa.justATestMethod();
结果为“假”。
如果我像这样重写方法“justATestMethod()”:
System.out.println(mapping.containsKey(new AlienSector(6, 'L')));
结果为“真”。
我得到“true”也改变了这行“loadMapFromFile”方法:
case "ALIENSECT":
Integer[] someValue = {5};
mapping.put(new AlienSector(row, col), someValue);
break;
这边:
case "ALIENSECT":
mapping.put(new Sector(row, col), new Integer[1]);
Integer[] aCazzo = {5};
mapping.put(new AlienSector(row, col), aCazzo);
break;
首先用Sector对象键填充HashMap,然后分配AlienSector对象键。
谁能解释一下为什么会这样? AlienSector 是 Sector 的子类,如果我只是实例化它的子类而不先用超类“扇区”的实例实例化键,为什么 Java 无法识别 HashMap 键中存在 Sector自己?
【问题讨论】:
-
请发布 AlientSector 和 Sector 类的 equals() 和 hashCode() 方法
标签: java inheritance hashmap polymorphism subclass