我有一个名为BaseCode的抽象类和两个名为Location and Department的具体类:
public abstract class BaseCode {
private Integer id;
...
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
...
}
public class Location extends BaseCode {
...
}
public class Department extends BaseCode {
...
}
我有一个名为BaseCodeCache的抽象类和两个名为LocationCache和DepartmentCache的具体类. LocationCache和DepartmentCache将使用Singleton.
public abstract class BaseCodeCache {
...
}
public class LocationCache extends BaseCodeCache {
...
}
public class DepartmentCache extends BaseCodeCache {
...
}
>在BaseCodeCache中,我想要一个java.util.Map,其值可以
可以是任何类型的BaseCode,即位置对象或部门
对象.
在LocationCache中,我希望java.util.Map存储Location对象.
在DepartmentCache中,我希望java.util.Map存储Department对象.
为此,我将以下代码放在BaseCodeCache中:
private Map idMap = new HashMap();
>我想有一种方法可以将值存储在
java.util.Map.
为此,我将以下代码放在BaseCodeCache中:
public void add(BaseCode baseCode) {
if (baseCode != null) {
idMap.put(baseCode.getId(), baseCode);
}
}
这就是我将其用于位置的方式:
Location location = new Location(); ...
LocationCache.getInstance().add(location);
这就是我将其用于Department的方式:
Department department = new Department(); ...
DepartmentCache.getInstance().add(department);
>我想要一种方法来获取java.util.Map中的所有值,如下所示:
一个java.util.List.
在LocationCache中,此方法应返回List< Location>.
在DepartmentCache中,此方法应返回List< Department>.
那就是我被困住的地方.我想在BaseCodeCache中创建此方法,但是当通过LocationCache调用此方法时,它将返回List< Location>.当通过DepartmentCache调用相同的方法时,它将返回List< Department>.可能吗?
我将此代码放在BaseCodeCache中:
public List getList() {
return new ArrayList(idMap.values());
}
但是上面的代码返回List< BaseCode>.当我这样称呼它时:
List allLocations = LocationCache.getInstance().getList();
然后,java将不允许其编译并给出以下错误消息:
Type mismatch: cannot convert from List to List
我可以通过获取List< BaseCode>来解决此问题.然后将其转换为List< Location>通过循环,但多数民众赞成在看起来不正确.
能做到吗