具有属性的组列表并添加另一个属性

时间:2015-11-23 09:37:49

标签: java arraylist hashmap

我有一个对象列表。我为每个具有类似属性的对象分配颜色ie.ParentId.I做了类似的事情: -

Map<String, String> idToColorMap = new HashMap<String, String>();
            int colorIndex = 0;
            for (int i = 0; i < myParentList.size(); i++)
            {
                if (myParentList.size() > 1 && !idToColorMap.containsKey(myParentList.get(i).getParentId())) {
                    Parent currentParent = myParentList.get(i);
                    currentParent.setColor(colorPallete[colorIndex]);
                    idToColorMap.put(currentParent.getParentId(), colorPallete[colorIndex]);

                    for (int j = i + 1; j < myFinalParentList.size(); j++) {
                        if (myParentList.get(j).getParentId().equals(currentParent.getParentId())) {
                            myParentList.get(j).setColor(colorPallete[colorIndex]);
                        }
                    }

                    if (++colorIndex == colorPallete.length) {
                        colorIndex = 0;
                    }
                } else {
                    myParentList.get(0).setColor(colorPallete[0]);
                    idToColorMap.put(myParentList.get(0).getParentId(), colorPallete[0]);
                }
            }

但是这样只有列表中第一个带有ParentId的项目被赋予颜色而不是所有具有相同ParentId的项目

1 个答案:

答案 0 :(得分:0)

问题来自你的测试。

// OK for parent[0] but not all other
if (myParentList.size() > 1 && !idToColorMap.containsKey(myParentList.get(i).getParentId())) { 
    ...
} 
// Will only set you first parent not all others
else {
    myParentList.get(0).setColor(colorPallete[0]);
    idToColorMap.put(myParentList.get(0).getParentId(), colorPallete[0]);
}

如果您没有遇到此parentId,则只能输入if。但是如果你已经遇到过那个,那么你去else,你只改变父[0]。

你应该分开考试。

编辑:

这是应该工作的东西(没有测试,可能需要进行一些小的修正)。另外:我不明白你的myFinalParentList是什么,所以我没有把它放在这里。只需在我的代码后添加你的foreach。如有必要

Map<String, String> idToColorMap = new HashMap<String, String>();
int colorIndex = 0;
String colorPallete = ...;
for (Parent parent : myParentList) {
    // if is not in idIdColorMap then I add it
    if (!idToColorMap.containsKey(parent.getParentId()) {
        idToColorMap.put(parent.getParentId(), colorPallete[colorIndex]);
        // increment colorIndex
        if (colorIndex + 1 == colorPallete.length) {
            colorIndex = 0;
        } else {
            colorIndex++;
        }
    }
    // Set Parent's Color
    parent.setColor(idToColorMap.get(parent.getId());
}