我的应用程序中有两个 map ,分别是“按 ID 划分的用户”和“按 ID 划分的管理员”。我使用它们通过 ID 获取用户:
Map<Id, Person> usersById = new HashMap<Id, Person>();
Map<Id, Person> managersById = new HashMap<Id, Person>();
Person me = usersById.get(myId);
这两个实体都是人,所以有时我需要通过 id 找到一个任意的人。是的,我可以在一张 map 中搜索,然后在另一张 map 中搜索:
Person findArbitraryPerson(Id id) {
Person candidate = usersById.get(myId);
if (candidate == null) {
candidate = managersById.get(myId);
}
return candidate;
}
但是,也许有更好的方法? 是的,我可以创建一个共同的人物 map 。但是每次它到达时我都必须向该 map 添加一个新的 Person 实例,然后将其删除等。是否可以创建一种“由两个 map 支持”的 map ,以自动更新其内容?正如我可以在 Collections 框架中创建一个由原始 map 支持的子 map 。
或者,可能有更好的解决方案?
最佳答案
我的 comment 的扩展(和/或结论)和@BrianRoach 的 comment :
public abstract class Person {
// general members and methods shared by managers and users
}
public class User extends Person {
// User specific members and methods
}
public class Manager extends Person {
// Manager specific members and methods
}
Map<Id,Person> map = new HashMap<Id, Person>();
map.put(new Id(), new Manager());
map.put(new Id(), new User());
或者(如果您愿意),只需在 Person 对象上添加一个 boolean 值成员:isManager
以及适当的 getter/setter。
关于java - Java 中是否有可能让一个 map 得到另外两个 map 的支持?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21304332/