Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating map of children objects from parent objects

Tags:

java

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)++);
}
like image 218
Mark Avatar asked Jan 22 '18 08:01

Mark


People also ask

Can we have child reference to parent object?

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.

Can you cast a parent object to child 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.

What is parent object and child object?

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.

Can parent class create object of child class?

In Simple Terms, Objects of Parent class can hold objects of child class.


1 Answers

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);
like image 66
Eran Avatar answered Nov 14 '22 21:11

Eran