I have an abstract class named BaseCode and 2 concrete classes named 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 {
...
}
I have an abstract class named BaseCodeCache and 2 concrete classes named LocationCache and DepartmentCache. LocationCache and DepartmentCache will be using Singleton.
public abstract class BaseCodeCache {
...
}
public class LocationCache extends BaseCodeCache {
...
}
public class DepartmentCache extends BaseCodeCache {
...
}
- In
BaseCodeCache, I want to have ajava.util.Mapwhose value can be any type ofBaseCodei.e.Locationobjects orDepartmentobjects.
InLocationCache, I want thejava.util.Mapto storeLocationobjects.
InDepartmentCache, I want thejava.util.Mapto storeDepartmentobjects.
To accomplish this, I put this code in BaseCodeCache:
private Map<Integer, BaseCode> idMap = new HashMap<Integer, BaseCode>();
- I want to have a method to store a value in the
java.util.Map.
To accomplish this, I put this code in BaseCodeCache:
public void add(BaseCode baseCode) {
if (baseCode != null) {
idMap.put(baseCode.getId(), baseCode);
}
}
This is how I would use it for Location:
Location location = new Location(); ...
LocationCache.getInstance().add(location);
This is how I would use it for Department:
Department department = new Department(); ...
DepartmentCache.getInstance().add(department);
- I want to have a method to get all values in the
java.util.Mapas ajava.util.List.
InLocationCachethis method should returnList<Location>.
InDepartmentCachethis method should returnList<Department>.
Thats where I am stuck. I want to create this method in BaseCodeCache but when this method is called via LocationCache then it returns List<Location> and when this same method is called via DepartmentCache then it returns List<Department>. Is it possible?
I put this code in BaseCodeCache:
public List<BaseCode> getList() {
return new ArrayList<BaseCode>(idMap.values());
}
But the above code returns List<BaseCode>. When I would call it this way:
List<Location> allLocations = LocationCache.getInstance().getList();
Then java will not let it compile and give this error message:
Type mismatch: cannot convert from
List<BaseCode>toList<Location>
I can get it fixed by getting List<BaseCode> and then converting it to List<Location> by looping but thats does not look right.
Can it be done?