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. However, I wanted to use a HashMap instead of if-else branches. I try to create Map<? extends Parent, Integer>
but it didn't work. 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)++);
}
The parent class can hold reference to both the parent and child objects. If a parent class variable holds reference of the child class, and the value is present in both the classes, in general, the reference belongs to the parent class variable. This is due to the run-time polymorphism characteristic in Java.
However, we can forcefully cast a parent to a child which is known as downcasting. After we define this type of casting explicitly, the compiler checks in the background if this type of casting is possible or not. If it's not possible, the compiler throws a ClassCastException.
Parent object and child object in the lookup relationship are determined purely on the requirement. Example: The object which has the more number of records will be the parent object and the object which has fewer records is considered as the child object.
In Simple Terms, Objects of Parent class can hold objects of child class.
You need the key of your Map
to be Class
(the type of the Parent
instance):
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With