我有一个父对象列表,想要统计子对象的出现次数。我知道可以使用 instanceof 运算符来计算每种对象类型的出现次数,如下所示。但是,我想使用 HashMap 而不是 if-else 分支。我尝试创建 Map<? extends Parent, Integer>
,但它没有起作用。有什么建议吗?
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)++);
}