简体   繁体   English

从父对象创建子对象的地图

[英]Creating map of children objects from parent objects

I have a list of parent objects where I want to count the occurrence of children objects. 我有一个父对象列表,我想在其中计算子对象的出现。 I know that I can use instanceof operator like shown below to count the occurrence of each object type. 我知道我可以使用如下所示的instanceof运算符来计数每种对象类型的出现。 However, I wanted to use a HashMap instead of if-else branches. 但是,我想使用HashMap代替if-else分支。 I try to create Map<? extends Parent, Integer> 我尝试创建Map<? extends Parent, Integer> Map<? extends Parent, Integer> but it didn't work. Map<? extends Parent, Integer>但是没有用。 Any suggestions? 有什么建议么?

class Parent {
// parent class
}

class ChildA extends Parent {
 // child class
}

class ChildB extends Parent {
 // child class
}

class ChildC extends Parent{
 // child class
}

int countChildA = 0;
int countChildB = 0;
int countChildC = 0;
for (Parent child : children)
{
    if (child instanceof ChildA)
    {
        countChildA++;
    }
    else if (child instanceof ChildB)
    {
        countChildB++;
    }
    else if (child instanceOf ChildC)
    {
        countChildC++;
    }
}

// what I'm looking for
Map<? extends Parent, Integer> map = new HashMap<>();
for (Parent child : children)
{
    map.put(child, child.getValue(child)++);
}

You need the key of your Map to be Class (the type of the Parent instance): 您需要将Map的键设置为ClassParent实例的类型):

Map<Class<? extends Parent>, Integer> map = new HashMap<>();

And instead of: 而不是:

map.put(child, child.getValue (child)++);

use: 使用:

if (map.containsKey(child.getClass())) {
    map.put(child.getClass(), map.get (child.getClass())+1);
} else {
    map.put(child.getClass(), 1);
}

or 要么

map.put(child.getClass(), map.getOrDefault(child.getClass(), 0) + 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM