-1

我想对系统中的数据进行深层复制。我有这样的课:

Class User{
    User mother;
    User father;
    User spouse;
}

创建单个记录后,我想像这样重建它们的引用:

Map<User, User> motherMap = new HashMap<User, User>();
Map<User, User> fatherMap = ...;
Map<User, User> spouseMap = ...;

//Now I want to populate User reference like this:
for(User user : motherMap.keySet) {
    //some other similar code;
    user.setMother(motherMap.get(user));
} 
for(User user : fatherMap.keySet) {
    //some other similar code;
    user.setFather(fatherMap.get(user));
}
for(User user : motherMap.keySet) {
    //some other similar code;
    user.setSpouse(spouseMap.get(user));
}

知道如何清理这种类似的代码吗?我想让我的代码更好,因为在实际代码中,用户之间有超过 10 个引用。Intellij 警告这种方法分析起来太复杂了,感觉只做复制粘贴...

4

2 回答 2

1

您可以这样做以从所有地图中创建一组所有键:

Set<User> allUsers = new HashSet<User>();

allUsers.addAll(motherMap.keySet());
allUsers.addAll(fatherMap.keySet());
allUsers.addAll(spouseMap.keySet());

for (User u : allUsers) {
    u.setMother(motherMap.get(u));
    u.setFather(fatherMap.get(u));
    u.setSpouse(spouseMap.get(u));
}
于 2013-06-26T18:17:42.020 回答
-2

您是否尝试过使用

instance of
于 2013-06-26T18:17:43.190 回答