I am writing one code using generic. I have one super class and two child class of said class.
I have one method which returns List of child(either list of first child objects or list of second child objects) object depending on some conditions.
Once I have this list, I also want to add one list(Child list) to this list.
pList = getParentList(); ( this method returns list of child objects depending of some conditions ,return type of getParentList method is List<? extends Parent>, and I can not change it)
cList = getChildList(); ( list of child objects)
cList.addAll(pList); // compile time error......
ॐ सर्वे जना: सुखिनो भवन्तु , तथास्तु |
'May the whole world be happy, so be it'
Is it possible to change the type of your cList also to List<? extends Parent>?
That won't work either. You are correct that you can't add an Unknown type that extends parent element to a list that takes child elements, because there is no way for the compiler to confirm if the element type is correct.
With the change that you suggested, you will be trying to add an unknown type that extends parent element into a list that takes a specific unknown type that extends elements. There is no way for the compiler to confirm if the two unknown types are the some type.
Keep in mind, <? extends Parent> doesn't mean that it will support any type that extends parent. It means that it is a specific type that extends parent, and the compiler doesn't know what it is.
If not I think you have to iterate through your parentsList, cast each element and add it to your cList..
The purpose of generics is so that you don't have to cast. If you do, why bother using generics? You are overriding the type checks anyway, so why bother having the compiler check. If you want a list that can hold any unknown type that extends parent, you need a list that holds a parent type -- as any child type of parent IS-A parent.
Bharat Makwana wrote:
Is it ok to type can child list to parent list? When i use type cast compiler does not sown error.
Basically, with generics, if the cast is okay, then you should not need to type cast it -- the compiler should allow it implicitly. If you have to type cast it, then you are telling the compiler that it is wrong, and frankly... as I said, if you need to do this frequently, then you shouldn't be using generics.
The reason type casting a child list to a parent list is a bad idea is that the parent list can hold any type of parent. And even though a child IS-A parent, not all parent types are childs. So, you will break any child references to that list.